从对象打印2D int向量
Printing a 2D int vector from an object
所以我很确定它有问题,因为它试图打印指针而不是值,但我不知道如何修复它。
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()
时编译器当前看到的是:
-
this->vect2d
,vect2d
的复杂拼写方式。注意,这是一个指针类型。vector<vector<int>>
类型的 -
this->vect2d[i]
,相当于*(vect2d + i)
,但不等同于(*vect2d)[i]
或vect2d->at(i)
!注意,这不是指针类型,但仍然是两个嵌套的向量。 - 因此,
.size()
在距离外部*vect2d
容器i
矢量大小的矢量上调用。很有可能,这是无效的内存,可能会出现段错误。
vector<vector<int>>*
类型的当您稍后执行vect2d[i][j]
时,它实际上相当于*(vect2d + i)[j]
,其行为应该与(vect2d + i)->at(j)
相同。但它不是vect2d->at(i).at(j)
!值得注意的是,它的类型是vector<int>
而不是int
。这就是你的错误消息的原因:没有可用的operator<<
来打印向量,所以编译器产生了相当难以理解的错误。
相关文章:
- 函数中的默认"常量<int>向量 &id"参数
- 将彼此平行的两个 int 向量的元素求和
- 向量的向量 int 向量
- 通过 fstream 函数初始化 int 向量??C++
- 如何调用一个函数,该函数用一个int向量取几个int
- 重载 C++ 运算符>>,以便我可以读取向量(向量<int>向量;
- 如何定义包含int向量的sruct的少算子
- 如何使用具有 pair<int,int 向量的元素unordered_set>
- OpenCV C++:从存储在 int 向量的索引中为垫子类型数据创建列范围
- 如何在不复制的情况下将只读向量传递给作为<int> pair<int,int>向量一部分的函数
- 在C++中,将两个长度相同的int向量转换为一个成对的int向量
- 使用int向量的向量对int向量进行基数排序
- 如何移除包含int向量的结构的向量
- 将一串数字解析为int向量的最快方法
- 删除c风格的int向量数组
- 从对象打印2D int向量
- 如何从文件中取出整数并将它们放入int向量中?
- 为什么 std::transform 不将 std::string 向量转换为无符号的 int 向量?
- 用C++11从点的向量中创建一个int向量
- 对已转换为字符串的int向量进行排序