You can create a map, which contains const values, then
create const map from it. Like this:
-------------------------
typedef std::map<int, const std::string> STRMAP;
int main()
{
STRMAP m1;
m1.insert(STRMAP::value_type(1, "one"));
m1.insert(STRMAP::value_type(2, "two"));
m1.insert(STRMAP::value_type(3, "three"));
// Error! Cannot modify const value.
m1[1] = "changed";
const STRMAP m2(m1);
// Error! Cannot modify const map.
m2.insert(STRMAP::value_type(4, "four"));
return 0;
}
-------------------------
HTH
Alex
There are three const there. The first, just makes the map a constant, i.e.
you can't insert or delete elements etc. This also affects the contained
values, you can only get const references to them.
The second is the key type and even value_type of std::map is already
pair<key_type const, data_type>. I think you can use a constant as
key_type, at least the SGI docs don't mention any restrictions like the
mention on the data_type.
The third type is a const on the data_type, which won't work because those
need to be assignable.
FYI, the (otherwise not relevant) documentation for the STL from SGI's
website explains which types have to fulfil which requirement, you might
want to take a look at them. I guess the docs at the MSDN do the same.
> In that case how to we populate it????????
The only const that works and does anything relevant is the first, which
means that you have a const map. You can only populate this via
initialisation, i.e. one of the constructors.
BTW: if you want to solve a real problem, you might want to tell us about
that instead of asking for some cornercase solution.
cheers
Uli
I have unsigned char constants defined in my class...
const unsigned char strKey1[] = "Key1";
const unsigned char strValue1[] = "Value1";
const unsigned char strKey2[] = "Key2";
const unsigned char strValue2[] = "Value2";
I want these data to be populated in a map..
If Key1 .. i should retrieve Value1...
If Key2 .. i should retrieve Value2...
How do i code this...???????
You can put pointers to char into map. However, you will
need to ensure that memory occupied by strings will remain
valid for lifetime of the map. Much simpler is to use
std::string class:
--------------------------------------------------------
typedef std::map<std::string, const std::string> STRMAP;
int main()
{
STRMAP m1;
m1.insert(STRMAP::value_type("key1", "one"));
m1.insert(STRMAP::value_type("key2", "two"));
m1.insert(STRMAP::value_type("key3", "three"));
const STRMAP m2(m1);
// retrieve value
STRMAP::const_iterator it = m2.find("key1");
if(it != m2.end())
std::cout << (*it).second;
else
std::cout << "not found";
return 0;
}
--------------------------------------------------------
HTH
Alex
In addition to what Alex recommended, there's Boost's map_list_of():
http://www.boost.org/libs/assign/doc/index.html
Theoretically you should be able to write:
const map<string, string> sample_map = map_list_of
("Key1", "Value1") ("Key2", "Value2");
Tom