6

I am trying to use a struct as a key for an unordered_map. I added the 'spaceship' operator to the structure, which solved errors I was getting with normal comparisons, such as "is struct 1 greater than struct 2?", etc. However, I am getting attempting to reference a deleted function when using it as a key for my map. From what understood, adding the spaceship operator should have allowed me to use the struct as the map key. What is wrong?

struct test
{
    uint32_t a;
    uint32_t b;

    auto operator<=>(const test&) const = default;
};

std::unordered_map<test, uint32_t> x; // Causes error
1
  • This question is similar to: C++ unordered_map using a custom class type as the key. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Mar 26 at 9:04

1 Answer 1

11

To use a structure as a key in an unordered_map, you need two things:

  • A "hasher", something that will take a const test & and compute a hash, which defaults to std:hash<test>, and

  • A comparison predicate, which defaults to std::equal_to<test>.

You've got the second one covered with your spaceship operator, but not the first. There is no std::hash<test>.

See C++ unordered_map using a custom class type as the key for an example as how to define your own hasher.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't you think this question is a duplicate of the one linked in your answer?
Yes, mostly. But not the bit about the comparator. (especially using <=>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.