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;
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;
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
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
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
.
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.