[英]why am I failing to push_back objects into c++ multidimensional vectors
所以我正在学习 c++,并为练习编写生活游戏。 我对向量和多维向量感到困惑。
class TABLE{
public:
int height;
int width;
vector<vector<CELL>> matrix_A;
vector<vector<CELL>> matrix_B;
bool current_matrix_is_a = true;
TABLE(int h,int w){
this->height=h;
this->width=w;
for (int y = 0; y < this->height; y++)
{
for (int x = 0; x < this->width; x++)
{
matrix_A[y].push_back(CELL(x,y));
matrix_B[y].push_back(CELL(x,y));
}
}
}
}
这段代码试图做的是制作一对二维向量,并填充每一行将一个单元格 object 用它在矩阵中的 x,y 实例化。 代码编译得很好,但是.exe 崩溃 - 当它到达 push_back 方法时。 我错过了一些基本的语法吗?
让我们将其简化为一个非常简单的示例:
vector<vector<int>> v;
for (int y = 0; y < 5; ++y) {
for (int x = 0; x < 5; ++x) {
v[y].push_back(make_some_int());
让我们做一个小实验,我们可以打印出外部向量的大小:
std::Cout << v.size() << std::endl;
我们得到什么? 0
,大小为 0: 所以当我们在第一轮这样做时:
v[y].push_back ...
我们在推回什么? 索引y
处不存在任何元素。 所以我们需要做到:
vector<vector<int>> v;
for (int y = 0; y < 5; ++y) {
vector<int> tmp; // Our tmp 1d vector
for (int x = 0; x < 5; ++x) {
tmp.push_back(make_some_int()); // This will work
}
v.emplace_back(std::move(tmp)); // Now we push back our 2d part.
// (std::move is a little c+++11 trick, feel free to google it.)
现在它将起作用!
matrix_A[y]
指的是一个不存在的元素,因为matrix_A
是空的。 同样matrix_B[y]
。
最简单的解决方案可能是在进入循环之前调整这些向量的大小。 这将创建您需要的元素:
matrixA.resize (this->height);
matrixB.resize (this->height);
for (int y = 0; y < this->height; y++)
...
您不需要指定this->
BTW,尽管这样做是无害的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.