Home >Backend Development >C++ >How to Use Pairs as Keys in Unordered Maps in C ?

How to Use Pairs as Keys in Unordered Maps in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 07:17:07718browse

How to Use Pairs as Keys in Unordered Maps in C  ?

Using Pairs as Keys in Unordered Maps

When attempting to declare an unordered_map where the keys are pairs (Vote = pair), many encounter an unexpected error:

Implicit instantiation of undefined template 'std::__1::hash, std::__1::basic_string > >'

This error arises because unordered_map relies on a hash function tailored to its key type. Since the default hash function is not applicable to pairs, you must provide a custom hash function.

For instance, consider the following custom hash function (pair_hash):

struct pair_hash {
    template <class T1, class T2>
    std::size_t operator() (const std::pair<T1, T2> &amp;p) const {
        auto h1 = std::hash<T1>{}(p.first);
        auto h2 = std::hash<T2>{}(p.second);
        return h1 ^ h2;
    }
};

This hash function combines the hash values of the pair's components using the XOR operator. To use it, modify the unordered_map declaration as follows:

using Vote = std::pair<std::string, std::string>;
using Unordered_map = std::unordered_map<Vote, int, pair_hash>;

This approach allows the creation of unordered maps with pairs as keys by providing a suitable hash function. However, it's worth noting that this simplistic implementation may not exhibit optimal hash properties and consider exploring Boost's hash_combine function or set hash_value for improved results.

The above is the detailed content of How to Use Pairs as Keys in Unordered Maps in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn