Reputation:
I need an 2_dimensional array in c++ which gets the dimension from user. How can I define an int 2_dimensional array in c++? I found something that define a 1_dimensional array then define other array in each element. like this:
int **ary = new int[sizeY];
for (int i = 0; i < sizeY; i++)
ary[i] = new int[sizeX];
Is there any other simple way?
Upvotes: 1
Views: 88
Reputation: 451
For me the simpliest method is to use vector. With it you can write code like this:
vector< vector<int> > arr(rows, vector<int>(cols, 0));
This will create a new 2d vector which you can use like array. As far as I am conserned this method is more preferable because you don't have to think about releasing memory.
Upvotes: 0
Reputation: 75697
std::vector<std::vector<int>> myarray(sizeY, std::vector<int>(sizeX));
Upvotes: 3
Reputation: 756
You should use a vector of a vector to do a 2 dimension array in c++
std::vector< std::vector<int> > myarray;
for(int i = 0; i < sizeY; i++)
{
myarray.push_back(std::vector<int>());
for(int j = 0; j < sizeX; j++)
{
myarray[i].push_back(0);
}
}
And you can access your element with myarray[y][x]
Upvotes: 0