4

Recently I was asked a question how to make a custom type as possible key for a stl::map.

Straight forward I answered them to overload the "<" operator function inorder to support custom type. Here is the link "custom type link"

When they asked me in which other ways this problem can be solved. I just hinted we might do it by overloading"==" operator also. But he was not happy with the answer.

Please help me to know, if there are any other ways to solve this problem "to make a custom type as a possible key for a map".

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

2 Answers2

4

std::maps require a less-than (or equivalent; less<key_type> is the default, per table 102), comparison for key types.

[C++11: 23.2.4/3]: The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator== on keys. That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false. For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.

So you can provide a comparator function that is not less<key_type>, to avoid operator< being called, but the end result as defined above must be the same. operator== is entirely irrelevant.

#include <iostream>
#include <map>

/**
 * A comparator that defines strict-weak ordering,
 * but is backwards!
 */
struct Comp
{
   bool operator()(const int& lhs, const int& rhs)
   { return rhs < lhs; }
};

int main()
{
   {
      std::map<int, char> m;        // uses default less<int> comparator
      m[0] = 'a';
      m[1] = 'b';
      m[2] = 'c';

      for (auto el : m)
         std::cout << el.second;    // "abc"
   }
   {
      std::map<int, char, Comp> m;  // uses my own comparator defined above
      m[0] = 'a';
      m[1] = 'b';
      m[2] = 'c';

      for (auto el : m)
         std::cout << el.second;    // "cba"  ... which is true ;)
   }
}

Live demo

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

Here std::maps with user-defined types as key you have a way to specialize std::map with a comparator function for your custom class.

Probably the interviewer was unhappy because == cannot provide a log(N) time method to access the values of the map. In fact you have to check the whole set of keys for equal keys if you only are provided with equality. The map cannot work with equality only.

Community
  • 1
  • 1
jimifiki
  • 5,377
  • 2
  • 34
  • 60