Monday, June 20, 2011


C++ 2011 and non rectangular arrays



Ever wanted to make a non rectangular array? Meaning for example, some multidimensional array where a[0] has 3 members and a[1] has 5 members, and so on.

You could do it with first building up the outermost array, and then add on each subarray separately, but you can't do it all in one shot at initialization time.

But enter C++ 2011 with initializer lists. You can initialize vectors of vectors with as many members at each level you want.

This works:

vector<vector<int>> a
(
{
{ 1, },
{ 1, 2, },
{ 1, 2, 3, },
{ 1, 2, 3, 4, 5, 6, 7, },
{ 1, 2, },
}
);

a.size() is 5, a[0].size() is 1, a[1].size() is 2, and so on.

Here's a complete example:
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> a
(
{
{ 1, },
{ 1, 2, },
{ 1, 2, 3, },
{ 1, 2, 3, 4, 5, 6, 7, },
{ 1, 2, },
}
);

void print(int t)
{
cout << t << ", ";
}

template<typename T>
void print(const T &t)
{
for (auto i = t.begin(); i != t.end(); ++i)
{
print(*i);
}
cout << '\n';
}

int main()
{
print(a);
return(0);
}



Output:

/tmp> g++-4.4 -Wall -o test test.cpp -std=c++0x
/tmp> ./test
1,
1, 2,
1, 2, 3,
1, 2, 3, 4, 5, 6, 7,
1, 2,

/tmp>

No comments: