Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用矢量创建二维阵列_C++_Vector - Fatal编程技术网

C++ 使用矢量创建二维阵列

C++ 使用矢量创建二维阵列,c++,vector,C++,Vector,我一直在尝试创建向量的2D数组。这是我正在做的一个例子 struct TILE { int a; }; TILE temp_tile; std::vector<TILE> temp_vec_tile; std::vector<std::vector<TILE>> tile; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { temp_tile

我一直在尝试创建向量的2D数组。这是我正在做的一个例子

struct TILE {
    int a;
};

TILE temp_tile;

std::vector<TILE> temp_vec_tile;
std::vector<std::vector<TILE>> tile;


for (int x = 0; x < 10; x++) {
    for (int y = 0; y < 10; y++) {

    temp_tile.a = x;
    temp_vec_tile.push_back(temp_tile);
    }
    tile.push_back(temp_vec_tile);
}

// Why does this not work? 

int x = tile[3][5].a;
struct-TILE{
INTA;
};
瓷砖温度;
标准::向量温度向量瓷砖;
std::向量块;
对于(int x=0;x<10;x++){
对于(int y=0;y<10;y++){
温度a=x;
临时向量。推回(临时向量);
}
瓷砖。向后推(临时瓷砖);
}
//为什么这不起作用?
int x=瓷砖[3][5].a;

有人能纠正我吗。告诉我它为什么不工作。

您无法清除行之间的临时向量,因此它将继续增长

因此,不是所有的行向量都有10个元素,第一个将有10个,接下来的20个,然后是30个,以此类推。前10个元素将始终是第一行的元素。因此,索引不会让您返回所需的元素


您可以在循环外部保留向量的大小,并直接存储在内部循环中,而不是将其推回到临时向量中,然后再推到外部向量中。

什么不起作用?您可能会得到一些意想不到的值,因为您创建了一个不断增长的
temp\u vec\u tile
。在将其插入外部向量后,您可能希望截断它,例如,使用
clear()

您所说的“不工作”是什么意思?JasonD能否请您提供一个正确的代码以供解释。