std::nth_element
来自cppreference.com
|
|
该页由英文版维基使用谷歌翻译机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击此处。 |
<metanoindex/>
| 在标头 <algorithm> 定义
|
||
| |
(1) | |
| |
(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
===。 返回值。===
。复杂性。
。线性平均在
std::distance(first, last).。为例。
运行此代码
#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