I need a std:map data structure that is read only, which means I have to fill it once with data and then only read those values, never change them or add additional ones.
My non-const version looks like this:
//in .h
#include <string>
#include <map>
std::map<std::string, int> myMap;
void initMap();
//in .cpp
#include "foo.h"
void initMap() {
myMap["Keys"] = 42;
}
Then I'd call initMap()
once in my code and be done.
Now I've read several questions here already and it seems non-trivial to achieve const-ness for the map.
Making it a std::map<std::string, const int>
won't allow me to fill it in the initMap()
.
Filling it with a non-const temp and the copy constructor on definition doesn't work either, as the copy constructor doesn't easily take the non-const version as input.
Making it a const std::map<std::string, int>
(which I could fill with a non-const copy during definition) would disable the use of the []
operator for value access.
So is there a way to achieve (value) const-ness and initialize the structure (preferably in the header file)?
BTW: Neither C++0x nor C++11 nor boost::
is an option.
Couldn't you use the insert()
method available for std::map
?
http://www.cplusplus.com/reference/map/map/insert/
Edit : (solution) myMap.insert(std::pair<std::string, const int>("Keys", 42));
As far as I understand it, the reason why this works is because the constructor for the pair, pair (const first_type& a, const second_type& b)
, initializes its members first
and second
using the constructors for first_type
and second_type
, taking a
and b
as their respective parameter.
With the solution you were trying to use, my comprehension is that myMap["Keys"] = 42;
initializes the member second
of the map
(of type const int
) using the default constructor for int
. Then a value is attempted to be assigned to that member. As this is done outside the constructor of the class map
, the const
declaration makes this impossible.
With the solution using insert()
, the members are initialized in the constructor of the pair
. Thus they can be declared const
. The same operation is done when the pair
is copied to the map
.