I am trying to do stable sort in C++ and my array is like this
{{first = "art zero", second = "let3 "}, {first = "own kit dig", second = "let2 "}, {first = "art can", second = "let1 "}}
sort(let.begin(), let.end(),
[](pair<string,string>& a, pair<string,string>& b) {
int comp = a.first.compare(b.first);
if(!comp) {
return a.second.compare(b.second);
} else {
return comp;
}
});
Why it did not sort lexicographically for the first value? And what does the return value really mean in C++ comparator? Thanks
If you simply choose std::map as your container, the default ordering provides storage in lexical sort order, e.g.
Example Use/Output
Sorting On Both You Cannot Use
map/mutimapIf you must sort telegraphically on both
.firstand.secondyou cannot usestd::map/std::multimap. They are limited to sorting on.firstfor storage. An alternative is astd::vector<std::pair<>>with your pairs of strings.You can implement your custom compare by writing a simple
boolCompare function as follows:Example Use/Output
After adding an additional
"art zero", "let2 "pair to force the sort on.second, you would have:If you can get away with only sorting on
.first, thenstd::map(orstd::multimap) handle the sorting for you. To sort on both.firstand.second, then the solution above isn't bad either.