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;
}
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"); }};
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)) ).
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.
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.
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