gpt4 book ai didi

C++ 标准排序文档问题

转载 作者:行者123 更新时间:2023-11-27 23:13:44 27 4
gpt4 key购买 nike

我的 C++ 标准文档拷贝记录了标准排序函数。

25.4.1.1排序

template<class RandomAccessIterator>
void sort(RandomAccessIterator first, RandomAccessIterator last);
...
Effects: Sorts the elements in the range [first,last).

Requires: RandomAccessIterator shall satisfy the requirements of ValueSwappable (17.6.3.2). The type of *first shall satisfy the requirements of MoveConstructible (Table 20) and of MoveAssignable

好的 - 但它不应该也要求所引用的元素也具有可比性吗?

我希望“Requires”子句包含如下内容:

“取消引用 RandomAccessIterator 产生的类型应该满足 LessThanComparable 的要求。”

或者更好

iterator_traits<RandomAccessIterator>::value_type 应该满足 LessThanComparable 的要求。”

因为 24.4.1 部分说“如果 Iterator 是迭代器的类型,则需要定义类型 ... iterator_traits<Iterator>::value_type

为什么不包括这样的语言。排序函数当然不能对不能比较的元素进行排序。

最佳答案

  • 好的 - 但它不应该也要求所引用的元素也具有可比性吗?

如果您在标准中向上滚动,您会发现排序算法的这些要求(在 § 25.4 下):

All the operations in 25.4 have two versions: one that takes a function object of type Compare and one that uses an operator<.

这意味着它已经在标准中强制要求使用 operator< 的类型自定义比较器。

自定义比较器有以下要求:

Compare is a function object type (20.8). The return value of the function call operation applied to an object of type Compare, when contextually converted to bool (4), yields true if the first argument of the call is less than the second, and false otherwise. Compare comp is used throughout for algorithms assuming an ordering relation. It is assumed that comp will not apply any non-constant function through the dereferenced iterator.

关于C++ 标准排序文档问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110051/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com