首页 文章

如何在C中打印出2D对象矢量?

提问于
浏览
3

我正在编写一个包含2D矢量对象的程序:

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

vector<Obj> a(100);

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

错误信息:

D:\ main.cpp:91:错误:'operator <<'不匹配(操作数类型为'std :: ostream '和'__gnu_cxx :: __ alloc_traits> :: value_type ')cout << b [i] [j]; ^

4 回答

  • 7

    也许就像下面

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

    您的问题与向量无关,它与将某些用户定义类型 Obj 的对象发送到标准输出有关 . 使用operator<<将对象发送到输出流时,如下所示:

    cout << b[i][j];
    

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

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

    甚至是 Obj 的矢量:

    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?

  • 6

    这与你的载体无关 .

    您正在尝试打印 Obj ,但您没有告诉您的计算机您希望它如何执行此操作 .

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

  • 1

    没有 cout::operator<<class Obj 作为右手边 . 你可以定义一个 . 最简单的解决方案是分别将 xy 发送到 cout . 但是使用基于范围的for循环!

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

相关问题