gpt4 book ai didi

c++ - 如何在 C++ 中打印出对象的二维 vector ?

转载 作者:太空狗 更新时间:2023-10-29 19:38:27 24 4
gpt4 key购买 nike

我正在编写一个程序,其中包含对象的二维 vector :

class Obj{
public:
int x;
string y;
};

vector<Obj> a(100);

vector< vector<Obj> > b(10);

我在 vector b 中存储了 vector a 的一些值。

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

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: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and '__gnu_cxx::__alloc_traits >::value_type {aka Obj}') cout << b[i][j]; ^

最佳答案

您的问题与 vector 无关,它与发送某些用户定义类型的对象有关Obj到标准输出。当您使用 operator<< 将对象发送到输出流时正如你所做的那样:

cout << b[i][j];

流不知道如何处理它,因为没有 12 overloads接受用户定义的类型 Obj .您需要重载 operator<<为你的类(class)Obj :

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

甚至是 Obj 的 vector 小号:

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

有关该主题的更多信息,请查看此 SO 帖子:
What are the basic rules and idioms for operator overloading?

关于c++ - 如何在 C++ 中打印出对象的二维 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com