Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a std::vector<std::pair<std::string,bool>> by the string?

How can I sort this vector by comparing the pair.first which is an std::string? (without providing a static compare function, nor use boost).

like image 250
jmasterx Avatar asked Jan 05 '11 23:01

jmasterx


2 Answers

std::vector<std::pair<std::string, bool> > v;
std::sort(v.begin(), v.end());

std::pair overloads operator< to sort first by the first element then by the second element. Thus, if you just sort the vector using the default sort ordering (operator<), you'll get your desired ordering.

like image 177
James McNellis Avatar answered Oct 23 '22 19:10

James McNellis


I really like James' answer, but there's one other option you might want to consider - just funnel everything into a std::map:

std::map<std::string, bool> myMap(v.begin(), v.end());

Or, if you have duplicate strings, a std::multimap:

std::multimap<std::string, bool> myMultiMap(v.begin(), v.end());

This does have the added advantage that if you then need to add or remove new key/value pairs, you can do so in O(lg n), as opposed to O(n) for the sorted vector.

If you really must use a vector, then go with James' answer. However, if you have a vector of pairs, there's a good chance that you really want a std::map.

like image 30
templatetypedef Avatar answered Oct 23 '22 19:10

templatetypedef