I need just dictionary or associative array string
=> int
.
There is type map C++ for this case.
But I need only one map forall instances(-> static) and this map can't be changed(-> const);
I have found this way with boost library
std::map<int, char> example =
boost::assign::map_list_of(1, 'a') (2, 'b') (3, 'c');
Is there other solution without this lib? I have tried something like this, but there are always some issues with map initialization.
class myClass{
private:
static map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
static map<int,int> myMap = create_map();
};
If you find
boost::assign::map_list_of
useful, but can't use it for some reason, you could write your own:It's useful to know how such things work, especially when they're so short, but in this case I'd use a function:
a.hpp
a.cpp
You could try this:
MyClass.h
MyClass.cpp
With this implementation your classes constant static map is a private member and can be accessible to other classes using a public get method. Otherwise since it is constant and can not change, you can remove the public get method and move the map variable into the classes public section. I would however leave the createMap method private or protected if inheritance and or polymorphism is required. Here are some samples of use.
I had edited my original post, there was nothing wrong with the original code in which I posted for it compiled, built and ran correctly, it was just that my first version I presented as an answer the map was declared as public and the map was const but wasn't static.
A function call cannot appear in a constant expression.
try this: (just an example)
The C++11 standard introduced uniform initialization which makes this much simpler if your compiler supports it:
See also this section from Professional C++, on unordered_maps.
A different approach to the problem:
This is more efficient, as there is no one-type copy from stack to heap (including constructor, destructors on all elements). Whether this matters or not depends on your use case. Does not matter with strings! (but you may or may not find this version "cleaner")
I did it! :)
Works fine without C++11