keywords: C++, std map, struct as key

C++ 98

std::map

override operator operator== and operator<.

Exmaple:

struct coord { 
    int x, y; 

    bool operator==(const coord &o) const {
        return x == o.x && y == o.y;
    }

    bool operator<(const coord &o)  const {
        return x < o.x || (x == o.x && y < o.y);
    }
};

Usage:

map<coord, int> m;
pair<coord, int> p((coord{0,0}),123);
m.insert(p);

Origin:
How can I use a struct as key in a std::map?
https://stackoverflow.com/questions/7204283/how-can-i-use-a-struct-as-key-in-a-stdmap

std:unordered_map

Exmaple:

struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};

namespace std {

template <>
struct hash<Key>
{
    std::size_t operator()(const Key& k) const
    {
        using std::size_t;
        using std::hash;
        using std::string;

        // Compute individual hash values for first,
        // second and third and combine them using XOR
        // and bit shifting:

        return ((hash<string>()(k.first)
        ^ (hash<string>()(k.second) << 1)) >> 1)
        ^ (hash<int>()(k.third) << 1);
        }
    };
}

int main()
{
  std::unordered_map<Key,std::string> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}

Origin:
C++ unordered_map using a custom class type as the key
https://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key

C++ 20

Default comparisons
#include <iostream>
#include <map>

using namespace std;

class Class1
{
public:
    Class1(int id);
    auto operator<=>(Class1 const &) const = default;

private:
    int id;
};

Class1::Class1(int id): id(id)
{}

int main()
{
    Class1 c1(1);

    map< Class1 , int> c2int;
    c2int[c1] = 12;

    return 0;
}

Origin: How can I use std::maps with user-defined types as key?
https://stackoverflow.com/a/70319881/1645289

Default comparisons (since C++20)
https://en.cppreference.com/w/cpp/language/default_comparisons


It is not true that people stop pursuing dreams because they grow old, they grow old because they stop pursuing dreams. ― Gabriel García Márquez