jkhadka
jkhadka

Reputation: 2543

Cannot make unordered_map work

I have written fairly simple code to check out unordered_pair

// unordered_map example
#include <iostream>
#include <unordered_map>
int main (){
    std::unordered_map<double, double> mymap = {
        {5,2.3},
        {7,34},
        {4,12}
    };
    std::cout<<":::: unordered_map ::::"<<std::endl;
    std::cout<<"5 ->"<<mymap[5]<<std::endl;
    std::cout<<"7 ->"<<mymap[7]<<std::endl;
    std::cout<<"4 ->"<<mymap[4]<<std::endl;
    std::cout<<"Done ! ";
    return 0;
}

I get the following error

unordered_map.cpp:5:37: error: non-aggregate type 'std::unordered_map<double, double>' cannot be initialized with an initializer list
        std::unordered_map<double, double> mymap = {
                                           ^       ~
1 error generated.
Compilation failed  

I am working on OSX and using geany.
Build command in Geany is :

g++ -Wall -c "%f"

Upvotes: 0

Views: 1107

Answers (1)

eerorika
eerorika

Reputation: 238281

unordered_map was introduced in the C++11 standard. If your g++ version supports it, you can enable c++11 standard with option -std=c++11

is there a way to use associative containers in older standards

std::map is an associative container. It exists in all c++ standards.

I was trying to use unordered_map because it is faster than map

unordered_map is faster in some cases. map is faster in other cases. Don't assume one way until you have measured.

However, using map without -std=c++11 still gives me same error as above

That's because you use list initialization which also requires c++11.

The old way of initializing a map:

std::map<int, int> m;
m[1] = 3;
m[2] = 2;
m[3] = 1;

Boost has a neat template for similar syntax to list initialization:

map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);

Upvotes: 2

Related Questions