Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 initialize map

Tags:

c++

c++11

map

I am trying to initialize a STL map using C++11 syntax but that doesn't seem to work. After initialization, when i try to access the element, it tries to call the private constructor of Foo. Did I miss something? It works if I use at. I am wondering if I could use operator[] to access initialized values...

#include <map>
#include <string>

class Foo{
public:
    int a, b;
    Foo(int a_, int b_){
        a = a_;
        b = b_;
    }

private:
    Foo(){};
};


int main(){

    std::map<std::string, Foo> myMap = { {"1", Foo(10,5)}, {"2", Foo(5,10)} };
    int b  = myMap["1"].b;    // it tries to call private constructor of Foo.
    return 0;
}
like image 414
Negative Zero Avatar asked Jun 07 '12 22:06

Negative Zero


People also ask

How do you initialize a map?

The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};

How do you initialize a map to 0?

What exactly do you want to initialize to zero? map's default constructor creates empty map. You may increase map's size only by inserting elements (like m["str1"]=0 or m. insert(std::map<std::string,int>::value_type("str2",0)) ).

Do we need to initialize map in C++?

A map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared.


1 Answers

When you use the operator[] on a map, you may use the operator to either get a value from the map or assign a value into the map. In order to assign the value into the map, the map has to construct an object of its value type, and return it by reference, so that you can use operator= to overwrite an existing object.

Consequently, the type has to be default constructible so that a new object can be created for you to assign into.

At run time, the constructor won't be called if the key already exists, but the compiler has no way of knowing whether you'll ever use operator[] to access a value that doesn't exist, so it requires the constructor to be public.

like image 74
Ken Bloom Avatar answered Oct 04 '22 03:10

Ken Bloom