Do tuples have an implicit lexicographical comparison?

家住魔仙堡 提交于 2019-12-08 17:37:45

问题


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 ?


回答1:


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

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

lexicographically compares the values in the tuple




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/23827036/do-tuples-have-an-implicit-lexicographical-comparison

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!