簡體   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