Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use is_transparent feature on a string literal with unordered_map from std::string?

Looking around on cppreference, I found that std::unordered_map gets efficient lookup functions from "equivalent keys".

I take that to mean that the equivalent key must have the same hash value. How can I provide that for a string literal I get the same hash value as for std::hash<std::string> without temporarily constructing an std::string and thereby making the whole point about the equivalent keys for naught?

like image 841
Johannes Schaub - litb Avatar asked Dec 03 '13 12:12

Johannes Schaub - litb


People also ask

Does unordered map allow duplicate keys?

We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_map the previous value corresponding to ...

Can we use pair in unordered_map?

Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair.

What does count function do in unordered_map?

The unordered_map::count() is used to count the number of elements in an unordered map with the specified key. The Unordered map does not allow repetition that's why this method will return the count to be either 1 or 0.

Are Keys sorted in unordered_map?

unordered_map is used to store elements as key,value pairs in non-sorted order.


2 Answers

That was an error in cppreference; there are no templated finds for unordered associated containers.

Compare, from n3690,

from §23.5.4.1[unord.map.overview]

// lookup
iterator find(const key_type& k);
const_iterator find(const key_type& k) const;
size_type count(const key_type& k) const;

from §23.4.4.1[map.overview]

// 23.4.4.5, map operations:
iterator find(const key_type& x);
const_iterator find(const key_type& x) const;
template <class K> iterator find(const K& x);
template <class K> const_iterator find(const K& x) const;
size_type count(const key_type& x) const;
like image 71
Cubbi Avatar answered Oct 11 '22 14:10

Cubbi


As others said, unordered associative containers don't support the is_transparent mode. Boost.MultiIndex hashed indices, on the other hand, allow for what you want, as explained in the documentation, in case it is an option for you to replace std::unordered_map with an equivalent construct based on a multi_index_container.

like image 28
Joaquín M López Muñoz Avatar answered Oct 11 '22 13:10

Joaquín M López Muñoz