简体   繁体   中英

Printing a 2D int vector from an object

So I'm pretty sure it's having issues because it's trying to print the pointer instead of the value, but I don't know how to fix it.

class cName {
private:
    std::vector< std::vector<int>> *vect2d;
public:
    // initializes vector that contains x number of vectors
    // that each contain y number of ints
    cName(int x,int y); 
    void printVector(int);
}

void cName::printVector(int x) {
    for(int i=0; i<x; i++) {
        //have to get size because 
        // the number of ints in the vector will change
        for(int j=0; j< this->vect2d[i].size(); j++) 
            std::cout << this->vect2d[i][j]<<" ";
        std::cout<<"\n";
    }
}

I'm having issues printing a 2d vector I use in a class I'm making. I get an error that says:

cannot bind 'std::ostream {aka std::basic_ostream<char>' 
lvalue to 'std::basic_ostream<char>&&'

Question:

Could someone explain me why is throwing me that error and help me fix it?

The vect2d member is a pointer to a vector of vectors of ints. You don't really need a pointer here, just use a vector of vectors of ints.

Your usage of this pointer does not produce any immediate errors because the subscript operator array[index] can be used on pointers. If you are not sure that your code is correct, prefer to use the range-checked .at(index) method for std::vector instances. Using an explicit method would have pointed you to your error, since there is no .at(index) method for pointers.

What the compiler currently sees when you call this->vect2d[i].size() is:

  • this->vect2d of type vector<vector<int>>* , a complicated way of spelling vect2d . Note that this is a pointer type.
  • this->vect2d[i] of type vector<vector<int>> , which is equivalent to *(vect2d + i) , but not to (*vect2d)[i] or vect2d->at(i) ! Note that this is not a pointer type, but still two nested vectors.
  • Therefore, the .size() is called on the vector that is i vector sizes away from your outer *vect2d container. Quite likely, this is invalid memory and could segfault.

When you later do vect2d[i][j] , that is actually equivalent to *(vect2d + i)[j] which should behave the same as (vect2d + i)->at(j) . But it is not vect2d->at(i).at(j) ! Notably, it is of type vector<int> rather than int . That is the cause of your error message: there's no available operator<< to print vectors, so the compiler produces that quite incomprehensible error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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