Home > Backend Development > C++ > Why Can't I Use `std::pair` as the Key in an `std::unordered_map` and How Do I Fix It?

Why Can't I Use `std::pair` as the Key in an `std::unordered_map` and How Do I Fix It?

Linda Hamilton
Release: 2024-12-07 02:57:12
Original
910 people have browsed it

Why Can't I Use `std::pair` as the Key in an `std::unordered_map` and How Do I Fix It?

Why can't I compile an unordered_map with a pair as key?

The issue faced here is the absence of a suitable hash function for the key type. To resolve this, provide a custom hash function for the pair key. Here's an example:

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

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;  // Simple example, for better results use boost.hash_combine
    }
};

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

With this custom hash function, you can now create an unordered_map without compilation errors. Note that the hash function provided here is simplistic for demonstration purposes. For real-world scenarios, consider using techniques like Boost's boost.hash_combine to enhance the quality of your hash function.

The above is the detailed content of Why Can't I Use `std::pair` as the Key in an `std::unordered_map` and How Do I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template