如何用c++中的指针初始化2D矢量

How to initialize a 2D vector with pointers in c++?

本文关键字:初始化 2D 矢量 指针 何用 c++      更新时间:2024-09-24

所以我试图在c++中初始化一个2D指针向量/指针矩阵(/3d向量?(。指向单元格对象的指针的二维矩阵。当运行代码时,我得到这个错误:

错误:没有用于调用的匹配函数'std::vectorstd::vector<单元格*>:push_back(std::vector&('
17|matrix.push_back(temp(;

注意:单元格是一个类

城市.hh:

std::vector <std::vector <Cell*>> matrix;
City(unsigned int M, unsigned int N);   

City.cc:

#include "City.hh"
City::City(unsigned int N, unsigned int M)
{
// size of "matrix"
this->M = M;
this->N = N;

for(unsigned int i = 0; i < M; i++)
{
vector <Cell> temp;
for(unsigned int j = 0; j < N; j++)
{
Cell cell = Cell();
temp.push_back(cell);
}
matrix.push_back(temp);
}
}

我建议您避免使用指针来保持对象之间的距离(由于各种原因(,而是这样做:

std::vector< std::vector< Cell > > matrix( M, std::vector< Cell >( N ) );