1

I'm trying to implement my own key comparator for std::map as follows:

auto cost_compare = [](const OffsetCoords& left, const OffsetCoords& right) { 
return (left == right); };

std::map<OffsetCoords, int, decltype(cost_compare)> cost_so_far(cost_compare);

where OffsetCoords is struct, vector of x, y values with overloaded operator==

code builds fine, but when I call cost_so_far.count(some_offsetcoords_variable) it throws exception 'Expression: invalid comparator'.

What's the proper way to do this?

szafir
  • 77
  • 8
  • 2
    Map needs less-than. – Richard Critten Jun 11 '16 at 22:43
  • http://stackoverflow.com/questions/9040689/stl-less-operator-and-invalid-operator-error – Alan Stokes Jun 11 '16 at 22:44
  • This question fails to meet the requirements for a [mcve], and therefore cannot be answered. – Sam Varshavchik Jun 11 '16 at 22:49
  • 1
    @RichardCritten: actually it doesn't. Using the less-than operator is an easy way to provide the binary predicate because `std::less` is used by default. You can use other binary predicates. However, the predicate used has to implement a _strict weak order_. In math, the symbol used to indicate the canonical strict weak order happens to be `<`. Where the choice of predicate matters, different symbols may be used, e.g., when any suitable strict weak order can be used the symbol is often a less-than within a circle. – Dietmar Kühl Jun 12 '16 at 01:27

1 Answers1

0

The binary predicate Comp used for std::map<Key, Value, Comp> needs to implement a strict weak order on objects of type Key. the strict refers to the fact that comp(x, x) yields false for all objects of type Key used with Comp. For the predicate you defined that is not the case.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380