Home > Backend Development > C++ > Can I Use Pairs as Keys in C Unordered Maps, and How?

Can I Use Pairs as Keys in C Unordered Maps, and How?

Linda Hamilton
Release: 2024-12-16 14:11:10
Original
129 people have browsed it

Can I Use Pairs as Keys in C   Unordered Maps, and How?

Can I use Pairs as Keys in Unordered Maps?

In C , you can encounter a compilation error when using an unordered_map with pair as its key. The issue arises from utilizing a custom type as the key, without providing an appropriate hash function for it.

Understanding the Error

The error you encounter is because unordered_map relies on a hashing mechanism to efficiently locate key-value pairs. However, it lacks a default hash function for complex types like pairs. The error message indicates that the compiler cannot implicitly instantiate an undefined hash function for your pair key type.

Solution: Providing a Hash Function

To resolve this issue, you need to define a hash function that calculates a unique hash value for your Vote pair type. This function should accept a pair as an argument and output a hash value.

Here's an example hash function implementation:

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;
    }
};
Copy after login

With this hash function, you can modify your code to create an unordered_map that uses pairs as keys:

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

Now, you can use this unordered_map as intended, avoiding the compilation error.

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