是 std::pair顺序定义明确吗?

发布于 2024-08-31 21:58:07 字数 171 浏览 2 评论 0 原文

看来我可以对 std::vector> 进行排序,它会根据 int 值进行排序。这是一个明确定义的事情吗?

std::pair 是否有基于其元素的默认排序?

It seems that I can sort a 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 its elements?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

纸短情长 2024-09-07 21:58:14

std::pair 使用字典比较:它将基于第一个元素进行比较。如果第一个元素的值相等,则将根据第二个元素进行比较。

C++03 标准(第 20.2.2 节)中的定义是:

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

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).
哀由 2024-09-07 21:58:14

根据我的 C++0x 标准副本,第 20.3.3.26 节,std::pair 定义了一个 operator<,对于两对 x 和 y,它返回

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

我不确定这是否也是 2003 年标准的一部分。我还应该注意,如果元素本身不是 LessThanComparable,则不会编译。

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.

挖鼻大婶 2024-09-07 21:58:14

SGI 的文档

比较运算符。它使用字典顺序比较:如果 x 的第一个元素小于 y 的第一个元素,则返回值为 true;如果 y 的第一个元素小于 x 的第一个元素,则返回值为 false。如果这两种情况都不是,则operator<返回 x 和 y 的第二个元素的比较结果。仅当 T1 和 T2 均为 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.

沉鱼一梦 2024-09-07 21:58:14

是的。 operator<() 是为 std::pair 定义的,假设 T1T2 > 本身具有可比性。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文