C++ 2 dimensional array with variable size rows

With C++11, you can do it easily with vectors (line breakes added for readability):

std::vector< std::vector <int > > arr = {
{1,2,3},
{4,5},
{6,7,8,9,0}
};

If you don’t have a C++11 compiler, it works the exact same way, but you will not be able to initialize them as easy. You can set elements individually:

std::vector< std::vector <int > > arr;//vector of vectors. Think of each element as of a "row"
std::vector<int> sub;//a temporary "row"
sub.push_back(1);
sub.push_back(2);
arr.push_back(sub);//Adding a "row" to the vector
sub.clear();//Making another one
sub.push_back(1);
sub.push_back(12);
sub.push_back(54);
arr.push_back(sub);//Adding another "row" to the vector

Or you can initialize each “row” with an ordinary array:

std::vector< std::vector <int > > arr;
static const int arr[] = {1,2,3,4};//A "row" as an ordinary array
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) ); //Setting a "Row" as a vector
arr.push_back(vec);//Adding the "row" to the vector of vectors. 

It’s not exactly possible to do what you want with ordinary arrays, since when you make an array[X][Y], it automaticaly is an X*Y matrix. You could, however, use an array of pointers:

int * array[3];
//also possible: int ** array =  new int*[3]; but don't forget to delete it afterwards.
int sub1[3] = {1,2,3};
int sub2[2] = {1,2};
int sub3[4] = {1,2,3,4};
array[0] = sub1;
array[1] = sub2;
array[2] = sub3;

and access elements with array[X][Y]. However, the vector solution is much better overall.

Leave a Comment