7

When sorting eg a vector of pairs :

vector<pair<int, double>> v;
sort(v.begin(), v.end());

You don't need to specify a sorting criterion to have a sorting based on the lexicographical order of the pairs since, when not elseway specified, a lexicographical comparison applies.

Is a similar behaviour standard for tuples as well ?

In VS2012 this compiles

vector<tuple<int, double, char>> tv;
sort(tv.begin(), tv.end());

but is it standard mandated to do so ?

Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153

3 Answers3

8

They do, see operator==,!=,<,<=,>,>=(std::tuple):

operator==
operator!=
operator<
operator<=
operator>
operator>=

lexicographically compares the values in the tuple

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
6

According to standard [20.4.2.7 Relational operators]: Yes

Overloaded operator for tuple:

 template<class... TTypes, class... UTypes>
 constexpr bool operator<(const tuple<TTypes...>& t, 
 const tuple<UTypes...>& u);

Returns: The result of a lexicographical comparison between t and u.

The result is defined as:

(bool)(get<0>(t) < get<0>(u)) ||(!(bool)(get<0>(u) < get<0>(t)) && ttail < utail)

where rtail for some tuple r is a tuple containing all but the first element of r. For any two zero-length tuples e and f, e < f returns false.

101010
  • 41,839
  • 11
  • 94
  • 168
4

In 20.4.2.7 Relational operators [tuple.rel]

template<class... TTypes, class... UTypes>
bool operator<(const tuple<TTypes...>& t, const tuple<UTypes...>& u);

Returns: The result of a lexicographical comparison between t and u. The result is defined as:

(bool)(get<0>(t) < get<0>(u)) || (!(bool)(get<0>(u) < get<0>(t)) && ttail < utail) 

where rtail for some tuple r is a tuple containing all but the first element of r. For any two zero-length tuples e and f, e < f returns false.

So no, they don't have an implicit one, they have an explicit

Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153