3

I can define a compare class for a map like this:

struct classcomp {
    bool operator() (const string& lhs, const string& rhs) const
    {
        if(lhs < rhs)
            return true;
        else 
            return false;
    }
};

but here lhs and rhs represent keys. What if I want to compare by values instead of key? How will I do that?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Jatin
  • 14,112
  • 16
  • 49
  • 78

2 Answers2

4

It's not about what you want; it's about what std::map wants. The ordering is based on the layout of elements in memory (usually in a tree structure) and it is this process that uses the comparator. Wishing this were not the case does not make it so!

It sounds to me like std::map as a container choice does not fit your requirements. Consult a container choice flow chart to decide what to do next.

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

The std::map type does not support comparison by values. If you want to compare by value, you should consider making a new multimap whose keys represent values in the old map and whose values represent keys in the old map.

That said, it sounds like you're trying to reorder the keys dynamically based on their values. In that case, you might want to look at priority queues supporting decrease-key, since that might be more aligned with what you're trying to do.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065