12/09/2013

Another method substitute for Initializer lists


Although, Initializer Lists was introduced in C++ 11, it was not applied to Visual Studio 2010.
So, I can't write below code, in VS2010.(and, may be same in VS2012)
vector<int> v = { 1, 2, 3, 4 };
So, I often used array rather than vector and non-member std::begin()/std::end(), since I prefer to use for_each, lambda, like below,
struct Actor
{
 string name;
 unsigned int age;
} actors[] = { {"joe", 19}, {"bach",24} };

for_each (std::begin(actors), std::end(actors), [](const Actor& a)
{
 //do something
 cout << ' ' << a.name;
 cout << ' ' << a.age;
});
Today, I read below article in StackOverFlow,
http://stackoverflow.com/questions/2236197/c-easiest-way-to-initialize-an-stl-vector-with-hardcoded-elements?rq=1

If I have to use only vector, this method will better solution, however, it will run for only primitive data type such as, int.
For user defined type, other method will be required.
Ref 1. http://en.cppreference.com/w/cpp/utility/initializer_list
Ref 2. http://oopscenities.net/2011/05/09/c0x-initializer-lists/


No comments:

Post a Comment