Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list initialization compile error

Tags:

c++

c++11

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 ?

like image 993
RoundPi Avatar asked Feb 06 '12 10:02

RoundPi


People also ask

What is initialization list in C?

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.

What is std :: initializer list?

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 .

What is uniform initialization in C++?

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.

What is braced init list in C++?

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.


1 Answers

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;
}
like image 84
RoundPi Avatar answered Sep 28 '22 13:09

RoundPi