Home > Backend Development > C++ > How to Resolve Unordered Map Compilation Errors with Pair Keys?

How to Resolve Unordered Map Compilation Errors with Pair Keys?

DDD
Release: 2024-12-16 06:41:25
Original
332 people have browsed it

How to Resolve Unordered Map Compilation Errors with Pair Keys?

Unordered Map Compilation Error with Pair Keys

When attempting to create an unordered map where the keys are pairs, you may encounter the following error:

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

This error occurs because unordered maps require hash functions to be defined for their key types. While the hash is available by default, a hash function is not provided for pair.

Solution: Providing a Custom Hash Function

To resolve this issue, you need to define a custom hash function for your pair key type. Here's an example implementation:

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

This hash function combines the hash values of the individual components of the pair using bitwise XOR (^).

Using the Custom Hash Function

Once you have defined the hash function, you can use it to create an unordered map with pair keys as follows:

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

Unordered_map um;
Copy after login

With this modification, the compilation error will no longer occur, and you will be able to use the unordered map as expected.

The above is the detailed content of How to Resolve Unordered Map Compilation Errors with Pair Keys?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template