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

How to Use Pairs as Keys in Unordered Maps?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 06:55:09209browse

How to Use Pairs as Keys in Unordered Maps?

Understanding Pair as Keys in Unordered Maps

When attempting to create an unordered map with a pair as the key, users may encounter a compilation error. This error arises from the lack of a suitable hash function for the custom key type, pair.

To resolve this issue, std::unordered_map requires users to provide a hash function specifically designed for the key type. This function is responsible for mapping the key to a unique identifier, which is crucial for fast and efficient retrieval.

Implementing a Custom Hash Function

A simple, albeit not optimal, hash function for a pair of std::hash-able types can be implemented as follows:

struct pair_hash {
    template <class T1, class T2>
    std::size_t operator()(const std::pair<T1, T2>& p) const {
        auto h1 = std::hash<T1>()(p.first);
        auto h2 = std::hash<T2>()(p.second);
        return h1 ^ h2; // Combine the hashes using a simple XOR
    }
};

Using the Custom Hash Function

Once the hash function is defined, it can be used with std::unordered_map to resolve the compilation error:

#include <unordered_map>
#include <functional>
#include <string>
#include <utility>

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

int main() {
    Unordered_map um;
}

Alternative Solutions

For broader support and better performance, consider utilizing libraries like Boost. Boost provides:

  • boost::hash_combine: A more robust method for combining hashes
  • set_hash_value function: Prepares hash functions for standard types like std::pair

By leveraging these options, users can ensure reliable hashing for their custom key types within std::unordered_map, enabling efficient and optimal code performance.

The above is the detailed content of How to Use Pairs as Keys in Unordered Maps?. 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