tags:

views:

665

answers:

4

From what I understand, the key in a value pair in an std::map cannot be changed once inserted. Does this mean that creating a map with the key template argument as const has no effect?

std::map<int, int> map1;
std::map<const int, int> map2;
+1  A: 

since int is copied by value this declaration of const has no sense. On other hand

std::map<const char*, int> map2;

dramatically changes a picture

Dewfy
Your example does not deal with the question: const char* is a non-constant pointer to a constant char, while the question deals with making the type constant (thus a constant pointer to a non-constant char): std::map< char* const, int >
David Rodríguez - dribeas
Point of post about sense of usage copy semantic, "const char*" copied by value, allows iteration over key, but disables modification of key.you declaration is kind of inconvenience. - it disables iteration over key, but allows modification: char *const v = "qwe"; *v = '6';//allowed!!! /*but this cause compiler error: v++;*/char *const v - just
Dewfy
A: 

As Dewfy said, with the example you gave, it doesn't matter since int is a built in type and it will be copied by value, but with char* it's a little different...

If you had

std::map<char *, int> map;

Then you can't insert a variable declared as const char* will fail

char * y = new char[4];
const char * x = "asdf";
std::map<char *, int> map;
map.insert(make_pair(y, 4)); //ok
map.insert(make_pair(x, 4)); //fail

with a

std::map<char*, int> map;

you can actually say

char * x = new char[1];
(*x) = 'a';
map<char*,int>::iterator it = map.begin();
cout<<it->first; //prints 'a'
(it->first)[0] = 'x'
cout<<it->first; //prints 'x'

with a

 std::map<const char *, int>

you'll be restricted to using

 map<const char*, int>::iterator
Charles Ma
See comment to Dewfy: const char* is a non-constant pointer to a constant char. You are not making the type constant, but rather changing completely the type (to point to a different type)
David Rodríguez - dribeas
+1  A: 

std::map constifies its key type anyway: std::map<int, int>::value_type is std::pair<const int, int>. If you add a const to the key type, const const int will simply collapse to const int.

sbi
+10  A: 

The answer to your title question is yes. There is a difference. You cannot pass a std::map<int, int> to a function that takes a std::map<const int, int>.

However, the functional behavior of the maps is identical, even though they're different types. This is not unusual. In many contexts, int and long behave the same, even though they're formally different types.

MSalters
The first answer that actually answers the question.
Tamás Szelei