Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a struct as key in a std::map?

Tags:

c++

c++11

stdmap

People also ask

Can I use pair as key in map C++?

Do you mean cout << mymap[make_pair(1,2)] << endl; ? (1,2) is non-sensical, at least in this context. You must have an std::pair to be used as your key, and that means following what @andre just commented. Yes!

What can be used as the key of map in C++?

We can use any of the data types as the data type of the key of the map. Even a user-defined data type can be used as key data type. Now, we will create a data structure that defines a new data type. And use it as a key for the map.

Where is the key in std::map?

The C++ function std::map::find() finds an element associated with key k. If operation succeeds then methods returns iterator pointing to the element otherwise it returns an iterator pointing the map::end().

What type of data structure is used in the implementation of C++' s map class?

map is often implemented using red-black trees, while unordered_map is often implemented using hash tables.


Try and make operator < const:

bool operator<(const coord &o)  const {

(Your = operator should probably be == operator and const as well)


By far the simplest is to define a global "less than" operator for your struct in stead of as a member function.

std::map uses - by default - the 'lessthan' functor which, in turn, uses the global "operator<" defined for the key type of the map.

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

As mentioned in the answer by Andrii, you can provide a custom comparison object to the map instead of defining operator< for your struct. Since C++11, you can also use a lambda expression instead of defining a comparison object. Moreover, you don't need to define operator== for your struct to make the map work. As a result, you can keep your struct as short as this:

struct coord {
    int x, y;
};

And the rest of your code could be written as follows:

auto comp = [](const coord& c1, const coord& c2){
    return c1.x < c2.x || (c1.x == c2.x && c1.y < c2.y);
};
std::map<coord, int, decltype(comp)> m(comp);

Code on Ideone


Another solution, which may be used for third-party data types, is to pass a Comparison object as third template parameter. example