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

jmasterx picture jmasterx · Jan 6, 2011 · Viewed 12.3k times · Source

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).

Answer

James McNellis picture James McNellis · Jan 6, 2011
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.