Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a const key for unordered_map

Tags:

c++

stl

I've been switching my code over from std::map to std::unordered_map where appropriate. With std::map, I typically write the following just to make sure the key cannot be modified:

std::map<const std::string, int>

Frankly, I never checked if this const was of any value. This has always compiled and worked with g++.

Now, with std::unordered_map, the following fails to link with g++ 4.5.1.

std::unordered_map<const std::string, std::string> m;
m["foo"] = "bar";

with this link error:

Undefined symbols: "std::hash<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const>::operator()(std::basic_string<char, std::char_traits<char>, std::allocator<char> >) const", referenced from:

The fix is simple, to remove const, but besides that, is there even a point in STL with any of the associative container classes to use a const key type? Are there no methods that let you get a reference to the key for any associative container?

like image 814
Blair Zajac Avatar asked Oct 22 '10 16:10

Blair Zajac


People also ask

Can unordered map have same keys?

Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key exists in the container, and zero otherwise.

Is unordered_map faster than map?

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order."

Can you iterate over unordered_map?

Iterating over a map by using STL Iterator: By creating an iterator of std::map and initializing it to the starting of map and visiting upto the end of map we can successfully iterate over all the elements of map.


1 Answers

The associative containers only expose the (key,value) pair as std::pair<const key_type, mapped_type>, so the additional const on the key type is superfluous.

like image 64
MSN Avatar answered Sep 26 '22 09:09

MSN