问题
I would like to get a two dimensional int array arr
that I can access via arr[i][j].
As far as I understand I could declare int arr[10][15];
to get such an array.
In my case the size is however variable and as far as I understand this syntax doesn't work if the size of the array isn't hardcoded but I use a variable like int arr[sizeX][sizeY]
.
What's the best workaround?
回答1:
If you don't want to use a std::vector of vectors (or the new C++11 std::array) then you have to allocate all sub-arrays manually:
int **arr = new int* [sizeX];
for (int i = 0; i < sizeX; i++)
arr[i] = new int[sizeY];
And of course don't forget to delete[]
all when done.
回答2:
c/c++ does not support multidimensional array. But it does support array of array:
//simulate 2-dimension array with 1-dimension array
{
int x = 20;
int y = 40;
int * ar = new int(x*y);
int idx_x =9;
int idx_y=12;
ar[idx_x + idx_y * x] = 23;
}
//simulate 2-dimension array with array of array
{
int x = 20;
int y = 40;
int**ar = new int*[y];
for(int i = 0; i< y; ++i)
{
ar[i] = new int[x];
}
ar[9][12] = 0;
}
回答3:
If you're looking for the solution in C, see this Stack Overflow thread: How do I work with dynamic multi-dimensional arrays in C?.
If C++ is okay, then you can create a 2D vector, i.e. a vector of vectors. See http://www.cplusplus.com/forum/general/833/.
回答4:
You can't, with array syntax. The language requires that you use compile time constants to create arrays.
回答5:
C++ does not have variable length arrays. You can consider using vector<vector<int> >
. It can be also accessed using arr[i][j]
.
回答6:
As fefe said you can use vector of vectors, e. g. :
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector< vector<int> > vec;
vector<int> row1;
row1.push_back(1);
row1.push_back(2);
vector<int> row2;
row2.push_back(3);
row2.push_back(4);
vec.push_back(row1);
vec.push_back(row2);
for( int ix = 0; ix < 2; ++ix)
for( int jx = 0; jx < 2; ++jx)
cout << "[" << ix << ", " << jx << "] = " << vec[ix][jx] << endl;
}
来源:https://stackoverflow.com/questions/8294102/proper-way-to-declare-a-variable-length-two-dimensional-array-in-c