如何在C 中打印一个对象的2D向量

How to print out a 2D vector of objects in C++?

本文关键字:一个对象 2D 向量 打印      更新时间:2023-10-16

我正在编写一个程序,其中包括对象的2D向量:

class Obj{
public:
    int x;
    string y;
};
vector<Obj> a(100);
vector< vector<Obj> > b(10);

我在向量b。

当我尝试这样打印出来时,我会出现错误:

for(int i=0; i<b.size(); i++){
    for(int j=0; j<b[i].size(); j++)
      cout << b[i][j];
    cout << endl;
}

错误信息:

d: main.cpp:91:错误:"操作员&lt;&lt;''无匹配(操作数类型是'std :: ostream {aka std :: basic_ostream}'和'__gnu_cxx :: __ __ __ alloc_traits> :: value_type {aka obj}'( cout&lt;&lt;B [i] [J]; ^

您的问题与向量无关,它与将某些用户定义的类型Obj的对象发送到标准输出有关。当您使用操作员将对象发送到输出流时。就像您所做的:

cout << b[i][j];

流不知道该如何处理,因为12个过载都不接受用户定义的类型Obj。您需要对类Objoperator<<超载:

std::ostream& operator<<(std::ostream& os, const Obj& obj) {
    os << obj.x  << ' ' << obj.y;
    return os;
}

甚至Obj S的向量:

std::ostream& operator<<(std::ostream& os, const std::vector<Obj>& vec) {
    for (auto& el : vec) {
        os << el.x << ' ' << el.y << "  ";
    }
    return os;
}

有关该主题的更多信息,请查看此信息:
运算符过载的基本规则和成语是什么?

这与您的向量无关。

您正在尝试打印Obj,但您没有告诉计算机如何希望它。

单独打印b[i][j].xb[i][j].y,或Obj的过载operator<<

没有cout::operator<<class Obj作为右侧。您可以定义一个。最简单的解决方案是将xy分别发送到cout。但是使用基于范围的陆面!

#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Obj {
public:
    int x;
    string y;
};
vector<vector<Obj>> b(10);
void store_some_values_in_b() {
    for (auto& row : b) {
        row.resize(10);
        for (auto& val : row) {
            val.x = 42; val.y = " (Ans.) ";
        }
    }
}
int main() { 
    store_some_values_in_b();
    for (auto row: b) {
        for (auto val : row) {
            cout << val.x << " " << val.y;
        }
        cout << endl;
    }
}

也许像下面的

for(int i=0; i<b.size(); i++){
    for(int j=0; j<b[i].size(); j++)
        cout << "(" << b[i][j].x << ", " << b[i][j].y << ") ";
    cout << endl;
}
相关文章: