无法创建 2D 数组

Can't create a 2d array

本文关键字:数组 2D 创建      更新时间:2023-10-16

我试图按照本指南 http://www.cplusplus.com/forum/general/107678/中的方式创建一个 2d 数组。

但是我得到了这个错误:

Error   1   
error C2664: 'void std::vector<std::vector<Square *,std::allocator<_Ty>>,std::allocator<std::vector<_Ty,std::allocator<_Ty>>>>::push_back(const std::vector<_Ty,std::allocator<_Ty>> &)' : 
cannot convert argument 1 from 'cocos2d::Vector<Square *> *' to 'std::vector<Square *,std::allocator<_Ty>> &&'  f:hoctaptechnologycocos2d-xcocos2d-x-3.2toolscocos2d-consolebinlightpuzzelclassesspritestable.cpp    63  1   LightPuzzel

这是我的代码:

vector<vector<Square*>> gameTable;
for (int i = 0; i < width; i++){
    auto squares= new Vector<Square*>;
    gameTable.push_back(squares);
    for (int j = 0; j < height; j++){
        auto *_square = new Square();
        gameTable[i].push_back(_square);
    }
}

如何修复此错误?

代码中有几个错误:

  1. 您在行中使用vector而不是Vector

     auto squares= new Vector<Square*>;
    
  2. 您正在添加指针而不是对象

     gameTable.push_back(squares);
    

您可以替换以下行:

 auto squares= new Vector<Square*>;
 gameTable.push_back(squares);

使用一行:

 gameTable.push_back(vector<Square*>());

来处理这两个错误。

若要创建 2D 数组,可以利用填充构造函数。

vector<vector<Square*> > gameTable (rowSize, vector<Square*>(columnSize, NULL));

然后,您可以使用嵌套循环来填充 2D 数组。

for (int i=0; i<rowSize; i++) {
    for (int j=0; j<columnSize; j++) {
        gameTable[i][j] = xxx;
    }
}

push_back() std::vector<>,而不是cocos2d::VectorgameTable的元素类型是 std::vector<Square*> ,这与要传入的类型不兼容。将类型签名更改为:

std::vector<Vector<Square*>> gameTable;

您还应该考虑使用 std::unique_ptr ,并emplace_back()这些元素:

std::vector<Vector<std::unique_ptr<Square>>> gameTable;
for (int i = 0; i < width; i++)
{
    gameTable.emplace_back();
    for (int j = 0; j < height; j++)
    {
        gameTable.at(i).push_back(new Square);
    }
}