如何在C 中打印一个对象的2D向量
How to print out a 2D vector of objects in C++?
我正在编写一个程序,其中包括对象的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
。您需要对类Obj
的operator<<
超载:
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].x
和b[i][j].y
,或Obj
的过载operator<<
。
没有cout::operator<<
将class Obj
作为右侧。您可以定义一个。最简单的解决方案是将x
和y
分别发送到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;
}
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 从多个源构造一个对象,包括一个对象向量
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 检查哪个对象调用了另一个对象的对象方法
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 包装一个对象并假装它是一个 int
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 如何使用函数将一个对象的输入复制到另一个对象中
- 选择一个元素而不是一个对象的数组的原因
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 如何在C 中打印一个对象的2D向量
- 创建一个动态2D数组来存储类对象
- 我如何从一个类与字符的2D向量转换到另一个对象与字符变量的2D向量
- 在2D场景中放大一个对象