views:

128

answers:

4

It seems that I can sort an std::vector<std::pair<int, std::string>>, and it will sort based on the int value. Is this a well defined thing to do? Does std::pair have a default ordering based on it's elements?

+12  A: 

std::pair uses lexicographic comparison: It will compare based on the first element. If the values of the first elements are equal, it will then compare based on the second element.

The definition in the C++03 standard (section 20.2.2) is:

template <class T1, class T2>
bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y);

Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second).
interjay
+1  A: 

Documentation from SGI

The comparison operator. It uses lexicographic comparison: the return value is true if the first element of x is less than the first element of y, and false if the first element of y is less than the first element of x. If neither of these is the case, then operator< returns the result of comparing the second elements of x and y. This operator may only be used if both T1 and T2 are LessThanComparable. This is a global function, not a member function.

Looks like it's actually a combination of both elements.

Chris H
+2  A: 

According to my copy of the C++0x standard, section 20.3.3.26, std::pair has an operator< defined such that for two pairs x and y, it returns

x.first < y.first || (!(y.first < x.first) && x.second < y.second)

I'm not certain if this is part of the 2003 standard as well. I should also note that this won't compile if the elements themselves are not LessThanComparable.

Kristo
A: 

Yes. operator<() is defined for std::pair<T1, T2>, assuming that both T1 and T2 are themselves comparable.

Dima