std::nth_element

来自cppreference.com
TranslationBot留言 | 贡献2012年10月25日 (四) 20:00的版本 (Translated from the English version using Google Translate)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

<metanoindex/>

 
 
算法库
受约束算法及范围上的算法 (C++20)
包含算法例如 ranges::copy, ranges::sort, ...
执行策略 (C++17)
排序和相关操作
划分操作
排序操作
二分搜索操作(在已划分范围上)
集合操作(在有序范围上)
归并操作(在有序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作
C 库

数值运算
(C++11)                       
在未初始化内存上的操作
 
在标头 <algorithm> 定义
template< class RandomIt >
void nth_element( RandomIt first, RandomIt nth, RandomIt last );
(1)
template< class RandomIt, class Compare >
void nth_element( RandomIt first, RandomIt nth, RandomIt last, Compare comp );
(2)
。部分排序的范围内[first, last)升序排列,使范围内的所有元素[first, nth)是“少”的范围内[nth, last)operator<的第一个版本使用比较的元素,第二个版本使用给定的比较函数comp。的元件放置在nth位置是完全相同的元素,该元素将在这个位置上,如果发生的范围完全排序.
原文:
Partially sorts the range [first, last) in ascending order so that all elements in the range [first, nth) are less than those in the range [nth, last). The first version uses operator< to compare the elements, the second version uses the given comparison function comp. The element placed in the nth position is exactly the element that would occur in this position if the range was fully sorted.
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

。参数。

Template:param list begin Template:param list item Template:param list item Template:param list cmp Template:param list hreq Template:param list req concept Template:param list req concept deref Template:param list end

===。 返回值。===

。 (无)。
原文:
(none)
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

。复杂性。

。线性平均在std::distance(first, last).
原文:
Linear in std::distance(first, last) on average.
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

。为例。

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

int main()
{
    std::vector<int> v{5, 6, 4, 3, 2, 6, 7, 9, 3};

    std::nth_element(v.begin(), v.begin() + v.size()/2, v.end());
    std::cout << "The median is " << v[v.size()/2] << '\n';

    std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater<int>());
    std::cout << "The second largest element is " << v[1] << '\n';
}

输出:

The median is 5
The second largest element is 7

。另请参阅。

Template:cpp/algorithm/dcl list partial sort copyTemplate:cpp/algorithm/dcl list stable sortTemplate:cpp/algorithm/dcl list sort