user4901806 user4901806 - 6 days ago 7
C++ Question

printing a 2d vector pointer

I created a 2d Vector like so :

int main(){
std::vector<std::vector<int> > my_2d_Vector;

for(int i = 0; i < 10; ++i){
std::vector<int> internal_vector;
for(int j; j < 10; ++j){
internal_vector.push_back(j);
}
my_2d_vector.push_back(internal_vector);
}
print_2d_vector(&my_2d_vector);
}


And i am trying to print it to the screen like so :

void print_2d_vector(std::vector<std::vector<int> > *my_vector){
for(int i = 0; i < my_vector->size(); ++i){
for(int j = 0; j < my_vector[i].size(); ++j){
std::cout << my_vector[i][j];
}
std::cout << "/n";
}
}


This looks fine too me.
But for some reason i dont understand, it tells me this when i try to compile it :
error : no match for 'operator<<' (operand types are std::ostream {aka std::basic_ostream<char>} and 'std::vector<int>')


I am confused as i am passing it an int from a vector and not the vector itself ?

Answer

It's because you pass a pointer to the function:

my_vector[i]

That doesn't actually access the vector, but rather the pointer. Then the second one, [j] accesses the actual vector. You need to dereference the pointer first to access the vector.

Why do you even require a pointer anyway? Just pass by value or use a reference if you need to have the function changing the vector:

void print_2d_vector(std::vector<std::vector<int> >& my_vector){
   for(int i = 0; i < my_vector->size(); ++i){
      for(int j = 0; j < my_vector[i].size(); ++j){
         std::cout << my_vector[i][j];
      }
    std::cout << "/n";
   }
}

And:

print_2d_vector(my_2d_vector);
Comments