繁体   English   中英

如何在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中存储了一些向量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 {aka std :: basic_ostream}'和'__gnu_cxx :: __ alloc_traits> :: value_type {aka Obj} ')cout << 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的矢量:

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

有关该主题的更多信息,请查看此SO帖子:
运算符重载的基本规则和习惯用法是什么?

这与你的载体无关。

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

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

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

也许就像下面

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM