4

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?

11
  • Can you use a multimap and switch key and value? Commented Jan 14, 2013 at 17:58
  • Use the keys passed to retrieve the values from the map? Commented Jan 14, 2013 at 17:58
  • 1
    Boost.Bimap Commented Jan 14, 2013 at 17:58
  • 1
    That compare class doesn't work. What about when lhs >= rhs? Commented Jan 14, 2013 at 17:58
  • 4
    It is not clear what you want to do. Can you provide a simple description of the problem you are trying to solve and how 'comparing by values instead of keys' would help? As it stands the question does not make much sense, key is what is used to compare, whether it is part of the value or not is another issue. Commented Jan 14, 2013 at 18:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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!

1 Comment

All wrapped up nicely in Boost.MultiIndex.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.