在 C++ 和 STL 中有多种方法可以在不进行内存操作的情况下定义二维数组,下面的代码说明了两种不同的方法:
int main ()
{
/**************
1 2 3
4 5 6
***************/
// Method 1
const int ROW = 2;
const int COL = 3;
int array1[ROW][COL];
for(int i=0; i<ROW; i++)
for(int j=0; j<COL; j++)
array1[i][j] = i*COL+j+1;
// Method 2
typedef vector<vector<int> > ARRAY;
ARRAY array2;
vector<int> rowvector;
for(int i=0; i<ROW; i++)
{
rowvector.clear();
for(int j=0; j<COL; j++)
rowvector.push_back(i*COL+j+1);
array2.push_back(rowvector);
}
return 0;
}
我的问题是:还有其他方法可以定义二维数组吗?哪一个是最有效的?谢谢!
最佳答案
在 C++11 中使用 std::array
:
std::array<std::array<int,3>,2> a {{
{{1,2,3}},
{{4,5,6}}
}};
一些用法:
a[0][2] = 13;
关于c++ - 如何在没有内存操作的情况下在 C++ 和 STL 中定义二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841170/