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>

2 comments:

MBBS in Philippines said...

Wisdom Overseasis authorized India's Exclusive Partner of Southwestern University PHINMA, the Philippines established its strong trust in the minds of all the Indian medical aspirants and their parents. Under the excellent leadership of the founder Director Mr. Thummala Ravikanth, Wisdom meritoriously won the hearts of thousands of future doctors and was praised as the “Top Medical Career Growth Specialists" among Overseas Medical Education Consultants in India.

Southwestern University PHINMAglobally recognized university in Cebu City, the Philippines facilitating educational service from 1946. With the sole aim of serving the world by providing an accessible, affordable, and high-quality education to all the local and foreign students. SWU PHINMA is undergoing continuous changes and shaping itself as the best leader with major improvements in academics, technology, and infrastructure also in improving the quality of student life.

Easy Loan Mart said...

Hi....
A rectangular array consists of a set of objects arranged in a similar way to a rectangular grid. It is one way of packing objects (e.g. eggs) efficiently. ... Supply students with drawings of various rectangular arrays of dots and ask them to count the number of dots in each array.
You are also read more Affordable Personal Loan