c++ 11 standard 8.5.4 example for list initializtion say:
std::map<std::string,int> anim = { {"bear",4}, {"cassowary",2}, {"tiger",7} };
But I have tried VC10, gcc 4.6 and Comeau, none of those compiler would let this pass ? Why is that ?
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .
Uniform initialization is a feature in C++ 11 that allows the usage of a consistent syntax to initialize variables and objects ranging from primitive type to aggregates. In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values.
initializer_list constructorsThe initializer_list Class represents a list of objects of a specified type that can be used in a constructor, and in other contexts. You can construct an initializer_list by using brace initialization: C++ Copy. initializer_list<int> int_list{5, 6, 7}; Important.
Thanks for all the answers in the comments.
I then checked back the c++ 98 and 03 standard and yea, 8.5.4 is definitely a new second in c++ 11 ! That's why it not being fully supported by all compilers.
After adding flag -std=c++0x with gcc 4.6.1 now this compiles fine.
Adding the testing code for anything who might need a reference:
#include <map>
#include <string>
#include <initializer_list>
#include <iostream>
using namespace std;
int main()
{
std::map<std::string,int> collection = {{"bear",4}, {"cassowary",2}, {"tiger",7}};
for(auto it: collection)
std::cout << it.first << " has value " << it.second << std::endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With