为啥我无法将对象 push_back 放入 C++ 多维向量中

Posted

技术标签:

【中文标题】为啥我无法将对象 push_back 放入 C++ 多维向量中【英文标题】:why am I failing to push_back objects into c++ multidimensional vectors为什么我无法将对象 push_back 放入 C++ 多维向量中 【发布时间】:2021-06-10 00:50:53 【问题描述】:

所以我正在学习 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));     
               
          
     

这段代码试图做的是创建一对二维向量,并填充每一行将用它在矩阵中的 x,y 实例化的单元格对象。 代码编译得很好,但是 .exe 崩溃 - 当它到达 push_back 方法时。 我错过了一些基本的语法吗?

【问题讨论】:

尝试用matrix_A.at(y).push_back(CELL(x,y));替换matrix_A[y].push_back(CELL(x,y)); 请发送minimal reproducible example。特别是,显示使用这个类的代码。 【参考方案1】:

让我们把它简化为一个非常简单的例子:

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.)

现在它可以工作了!

【讨论】:

【参考方案2】:

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-&gt; BTW,尽管这样做是无害的。

【讨论】:

以上是关于为啥我无法将对象 push_back 放入 C++ 多维向量中的主要内容,如果未能解决你的问题,请参考以下文章

为啥不能在 2D 向量中 push_back? C++

无法将派生类 push_back() 推入 C++ 中的 STL 列表

为啥我不能将 B 的超类对象放入 Container<?超级B>? [复制]

C++ - 没有匹配的成员函数调用“push_back”

使用 push_back 将整数放入字符串

为啥当 T=std::string custom Vector C++ 时在 push_back(T&&) 上出现 SIGSEGV 错误