Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C++;?_C++_Vector - Fatal编程技术网

C++ 如何在C++;?

C++ 如何在C++;?,c++,vector,C++,Vector,我正在编写一个程序,其中包括一个二维物体矢量: class Obj{ public: int x; string y; }; vector<Obj> a(100); vector< vector<Obj> > b(10); 类Obj{ 公众: int x; 弦y; }; 载体a(100); 向量b(10); 我在向量b中存储了向量a的一些值 当我尝试这样打印时,会出现一个错误: for(int i=0; i<b.size(); i

我正在编写一个程序,其中包括一个二维物体矢量:

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

vector<Obj> a(100);

vector< vector<Obj> > b(10);
类Obj{
公众:
int x;
弦y;
};
载体a(100);
向量b(10);
我在向量b中存储了向量a的一些值

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

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

for(inti=0;i这与向量无关

您正试图打印一个
Obj
,但您没有告诉计算机您希望它如何打印

单独打印
b[i][j].x
b[i][j].y
,或者重载
操作符,可能如下所示

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;
}

for(int i=0;i您的问题与向量无关,它与发送对象有关将某个用户定义的类型
Obj
发送到标准输出。当您使用将对象发送到输出流时,没有
cout::operator,也没有对象的2D向量。您有对象的向量。如果对象不在“2D向量”内,您将如何打印该对象?在一个向量中并不能神奇地转换一个类型。要了解更多关于未来的信息,请提供一个完整的程序。这个答案缺少解释。
cout << b[i][j];
std::ostream& operator<<(std::ostream& os, const Obj& obj) {
    os << obj.x  << ' ' << obj.y;
    return os;
}
std::ostream& operator<<(std::ostream& os, const std::vector<Obj>& vec) {
    for (auto& el : vec) {
        os << el.x << ' ' << el.y << "  ";
    }
    return os;
}
#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;
    }
}