gpt4 book ai didi

c++ - std::nth_element(a.begin(), a.end(), a.end()) 有什么作用?

转载 作者:可可西里 更新时间:2023-11-01 18:37:09 36 4
gpt4 key购买 nike

我在 http://www.sgi.com/tech/stl/nth_element.html 阅读了 std::nth_element 的描述

template <class RandomAccessIterator>
void nth_element(RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last);

注意前提是

  1. [first, nth) 是一个有效范围。
  2. [nth, last) 是一个有效范围。

我的问题是:

调用 std::nth_element(a.begin(), a.end(), a.end()) 是否有效?如果有,它的作用是什么?无论如何,它不违反上述先决条件。语言标准(或其他文档)中的任何地方声明 nth 必须指向 a 中的元素?

最佳答案

它是有效的,可能是空操作,但标准不保证。使用给定的数据,两个先决条件变为:

[a.begin(), a.end()) is a valid range.
[a.end(), a.end()) is a valid range.

这两个都是真的,虽然第二个间隔是空的。来自标准 25.3.2/1:

After nth_element the element in the position pointed to by nth is the element that would be in that position if the whole range were sorted. Also for any iterator i in the range [first, nth) and any iterator j in the range [nth, last) it holds that: !(*i > *j) or comp(*j, *i) == false.

如果对整个范围进行排序,则原始 a.end() 将位于 a.end() 并且对于第二部分,范围 [nth , last) 是空的,所以没有要计算 !(*i > *j)comp(*j, *i) == false< 的元素 条件。

关于c++ - std::nth_element(a.begin(), a.end(), a.end()) 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245359/

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