Is std::pair<int, std::string> ordering well-defined?

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

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.


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.

Tags:

C++

Sorting

Stl