从对象打印2D int向量

Printing a 2D int vector from an object

本文关键字:int 向量 2D 打印 对象      更新时间:2023-10-16

所以我很确定它有问题,因为它试图打印指针而不是值,但我不知道如何修复它。

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

我在打印我在制作的类中使用的2d矢量时遇到了问题。我得到一个错误,说:

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

问题:

有人能解释一下为什么给我这个错误,并帮助我修复它吗?

vect2d成员是指向int型向量的vector对象的vector对象的指针。这里其实不需要指针,只需使用int型向量的向量的向量。

使用该指针不会立即产生任何错误,因为下标操作符array[index]可以在指针上使用。如果您不确定您的代码是否正确,那么更愿意对std::vector实例使用范围检查的.at(index)方法。使用显式方法会指出错误,因为指针没有.at(index)方法。

当你调用this->vect2d[i].size()时编译器当前看到的是:

    vector<vector<int>>*类型的
  • this->vect2d, vect2d的复杂拼写方式。注意,这是一个指针类型。vector<vector<int>>类型的
  • this->vect2d[i],相当于*(vect2d + i),但不等同于(*vect2d)[i]vect2d->at(i) !注意,这不是指针类型,但仍然是两个嵌套的向量。
  • 因此,.size()在距离外部*vect2d容器i矢量大小的矢量上调用。很有可能,这是无效的内存,可能会出现段错误。

当您稍后执行vect2d[i][j]时,它实际上相当于*(vect2d + i)[j],其行为应该与(vect2d + i)->at(j)相同。但它不是vect2d->at(i).at(j) !值得注意的是,它的类型是vector<int>而不是int。这就是你的错误消息的原因:没有可用的operator<<来打印向量,所以编译器产生了相当难以理解的错误。