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>

C++ 2011 and __func__



So what happens to __func__ in different scopes? How about GCC's extension for pretty function names?

#include <iostream>
using namespace std;

namespace
{
void f()
{
auto func = []()->const char *{ return(__func__); };
auto func2 = []()->const char *{ return(__PRETTY_FUNCTION__); }; //GCC extension

cout << func() << '\n'
<< func2() << '\n'
<< __func__ << '\n'
<< __PRETTY_FUNCTION__ << endl;
}
}

int main()
{
f();
cout << __func__ << '\n'
<< __PRETTY_FUNCTION__ << endl;

return(0);
}



Output:

/tmp> g++-4.5 -Wall -o test test.cpp -std=c++0x
/tmp> ./test
operator()
<unnamed>::f()::<lambda()>
f
void<unnamed>::f()
main
int main()
/tmp>

/tmp> g++-4.6 -Wall -o test test.cpp -std=c++0x
/tmp> ./test
operator()
{anonymous}::f()::<lambda()>
f
void {anonymous}::f()
main
int main()
/tmp>