What is difference between const and non const key?

C++KeyLanguage LawyerKey ValueStdmap

C++ Problem Overview


What is the difference between the following two lines?

map<int, float> map_data;
map<const int, float> map_data;

C++ Solutions


Solution 1 - C++

  • int and const int are two distinct types.

  • std::map<int, float> and std::map<const int, float> are, similarly, different types.

The difference between std::map<const int, float> and std::map<int, float> is, to a degree, analogous to the difference between, say, std::map<int, float> and std::map<std::string, float>; you get a fresh map type for each.

In the non-const case, the internal key type is still non-const int:

std::map<const int, float>::key_type       => const int
std::map<int, float>::key_type             => int

However, map keys are semantically immutable, and all map operations that allow direct access to keys (for example, dereferencing iterators, which yields value_type) does constify the key_type:

std::map<const int, float>::value_type => std::pair<const int, float>
std::map<int, float>::value_type       => std::pair<const int, float>

So the difference may be largely invisible to you in every way that matters, if your implementation allows it.

That's not always the case, though: the standard officially requires your key type to be copyable and moveable, and some implementations re-use map nodes; under those implementations, attempting to use a const key simply won't work.

Solution 2 - C++

The key is already const, so it is redundant to write const in this case. Once an element is entered, its key cannot be changed.


Edit:

As mentioned in the comments, there is difference between the two lines. For example, if you write a function that accepts map<const int, int>, you can't pass to it map<int, int> since they're different types.

But note that although they are different types, they behave the same since the key in a map is a const anyway...

So in conclusion.. The only difference is that they are two different types, you shouldn't care about anything else.

Solution 3 - C++

The difference is that the second variant will set the key type for the map as const int. From the "modifiability" point of view this is redundant, since the map already stores its keys as const objects.

However, this can also lead to unexpected and non-obvious differences in the behavior of these two maps. In C++ a template specialization written for type T is different from specialization written for type const T. That means the above two versions of the map might end up using different specializations of various "satellite" templates that depend on the key type. One example is the key comparator predicate. The first one will use std::less<int> while the second one will use std::less<const int>. By exploiting this difference you can easily make these maps to sort their elements in different order.

Issues like that are more obvious with the new C++11 containers like std::unordered_map. std::unordered_map<const int, int> will not even compile, since it will attempt to use a std::hash<const int> specialization for hashing the keys. Such specialization does not exist in the standard library.

Solution 4 - C++

const can't be altered once set. And yes as per docs & other answer you should remember that key is const already.

Link: http://www.cplusplus.com/reference/map/map/ Link: http://en.cppreference.com/w/cpp/container/map

Solution 5 - C++

While the behaviour of your application will typically be the same, it makes a difference to some compilers you might use. The more specific example of what brought me to this page in the first place:

Explicitly specifying a map as map<const key, value> builds successfully with the gnu toolkit;

However it crashes a Studio12 Solaris x86 build.


map<key, value> builds successfully on both. Behaviour of the application is unchanged.

Solution 6 - C++

Const keys can be helpful if the keys are pointers. Using const keys won't let you modify the pointed object when accessing the keys, consider this:

#include <map>
#include <string>

int glob = 10;

int main() {
	std::map<const int*, std::string> constKeyMap { { &glob, "foo"} };
	std::map<int*, std::string> keyMap { { &glob, "bar" } };
	
	for(const auto& kv : keyMap) { *(kv.first) = 20; }; // glob = 20
	for(const auto& kv : constKeyMap) { *(kv.first) = 20; }; // COMPILE ERROR
	
	return 0;
}

Solution 7 - C++

const refers to a constant, that, once defined, can't be altered then... non const key is subjected to change... or cant even change, it's just that "no change" is guaranteed in const (once defined), and "change" may or may not occur in non const stuff.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullPoiиteяView Question on Stackoverflow
Solution 1 - C++Lightness Races in OrbitView Answer on Stackoverflow
Solution 2 - C++MarounView Answer on Stackoverflow
Solution 3 - C++AnTView Answer on Stackoverflow
Solution 4 - C++ShumailView Answer on Stackoverflow
Solution 5 - C++blgtView Answer on Stackoverflow
Solution 6 - C++SiimKallasView Answer on Stackoverflow
Solution 7 - C++r0u9hn3ckView Answer on Stackoverflow