【问题标题】:How to print out a 2D vector of objects in C++?如何在 C++ 中打印出对象的二维向量?
【发布时间】:2018-07-28 08:02:02
【问题描述】:

我正在编写一个包含二维对象向量的程序:

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::value_type {又名 Obj}') cout

【问题讨论】:

  • 没有对象的二维向量这样的东西。你有一个对象向量的向量。
  • 如果对象不在“2D 矢量”内,您将如何打印它?位于向量内部并不会神奇地转换类型。
  • 了解更多关于range for loops
  • 以后,请提供一个完整的程序。 minimal reproducible example

标签: c++ vector


【解决方案1】:

这与你的向量无关。

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

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

【讨论】:

    【解决方案2】:

    可能像下面这样

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

    【讨论】:

    • 这个答案缺少解释。
    【解决方案3】:

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

    cout << b[i][j];
    

    流不知道如何处理它,因为12 overloads 都不接受用户定义的类型Obj。您需要为您的班级Obj 重载operator&lt;&lt;

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

    甚至是Objs的向量:

    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?

    【讨论】:

      【解决方案4】:

      没有cout::operator&lt;&lt;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;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 2012-08-31
        • 2023-03-04
        相关资源
        最近更新 更多