ahhhhhjulie ahhhhhjulie - 1 month ago 9
C++ Question

Custom sort ordered map with tuple as keys

Say I define my tuple as follows:

typedef tuple<string, string> bigram;


And my map maps tuples to integers:

map<bigram, int> mymap;


How can I custom my comparator so that
mymap
is sorted according to the alphabetical order of the first string in a
bigram
?

I'm thinking somewhere along the lines of

map<bigram, int, greater<bigrams[0]>> mymap;

Answer

First - alphabetical order means you want less rather than greater. Second, the default sort order for tuple<string, string> should just work for you. Note: the various suggestions people are giving probably don't do what you want. They'd all compare {"foo", "bar"} and {"foo", "baz"} as equal when you probably want them to be treated as different objects. If you want reverse sorting, you should be able to do map<bigram, int, std::greater<bigram>> otherwise stick to simply map<bigram, int>.

For reference the definition of the comparison operators that come for free with tuple: http://en.cppreference.com/w/cpp/utility/tuple/operator_cmp