无法创建 2D 数组
Can't create a 2d array
我试图按照本指南 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);
}
}
如何修复此错误?
代码中有几个错误:
-
您在行中使用
vector
而不是Vector
auto squares= new Vector<Square*>;
-
您正在添加指针而不是对象
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::Vector
。gameTable
的元素类型是 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);
}
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何打印 2D 字符数组C++
- 如何将数组 2d 作为参数从函数传递并返回数组 2d 此函数
- 数组 2D 多个值
- 创建数组数组 (2D),而无需在 Java 中初始化内部数组
- 如何在C++中将文本文件传输到数组2D
- 从同一类的另一个方法调用数组2D-C++
- 获取地址在数组2d中的位置