3

I'm writing a program which includes a 2D vector of objects:

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

vector<Obj> a(100);

vector< vector<Obj> > b(10);

I've stored some values of vector a in vector b.

I get an error when I try to print it out like this:

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

error info:

D:\main.cpp:91: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and '__gnu_cxx::__alloc_traits >::value_type {aka Obj}') cout << b[i][j]; ^

theg
  • 469
  • 2
  • 6
  • 21

4 Answers4

9

Your problem is not related to vectors, it is related to sending object(s) of some user defined type Obj to the standard output. When you send an object to the output stream using the operator<< as you do with:

cout << b[i][j];

the stream does not know what to do with it as none of the 12 overloads accepts a user defined type Obj. You need to overload the operator<< for your class Obj:

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

or even a vector of Objs:

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

For more info on the subject check out this SO post:
What are the basic rules and idioms for operator overloading?

Ron
  • 14,674
  • 4
  • 34
  • 47
6

This has nothing to do with your vectors.

You are trying to print an Obj, but you didn't tell your computer how you would like it to do that.

Either print b[i][j].x and b[i][j].y individually, or overload operator<< for Obj.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

There is no cout::operator<< that takes a class Obj as a right hand side. You could define one. Simplest solution is to send x and y to cout separately. But use range-based for-loops!

#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;
    }
}
Jive Dadson
  • 16,680
  • 9
  • 52
  • 65
1

Maybe like below

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;
}
273K
  • 29,503
  • 10
  • 41
  • 64