Home > Blockchain >  Using A Struct As Key For std::unordered_map
Using A Struct As Key For std::unordered_map

Time:07-21

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

CodePudding user response:

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.

  • Related