Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

nth_element

函数模板  <algorithm>
default (1)
template <class RandomAccessIterator>
  void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
                    RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>
  void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
                    RandomAccessIterator last, Compare comp);

对范围内的元素进行排序

重新排列[first,last),nth位置的值就是把所有元素排序后在nth位置的值.

剩下的其他元素没有任何特定的顺序,除了nth元素之前的元素都不大于它, nth元素之后的元素都不小于它。

第一个版本使用operator<比较元素,第二个版本使用comp操作符比较元素。

☲  参数


first, last
指向一个序列初始和最终位置的随机访问迭代器。使用的范围是[first,last), 它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

nth
C++11: 指向范围[first,last)内包含排序元素的位置的随机访问迭代器。
注意,调用前nth所指向的元素的值是不相关的。

C++14: 指向范围[first,last)内包含排序元素的位置的随机访问迭代器。
如果指向last,则函数调用无效。
注意,调用前n所指向的元素的值是不相关的.

comp
二元函数,它接受范围中的两个元素作为参数,并返回可转换为bool的值。 返回的值表明作为第一个参数传递的元素是否按照其定义的严格弱排序先于第二个参数。
函数不能修改它的任何参数。
它可以是函数指针,也可以是函数对象。

☉  返回值



none.

☣  示例



// nth_element example
#include <iostream>     // std::cout
#include <algorithm>    // std::nth_element, std::random_shuffle
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

int main () {
  std::vector<int> myvector;

  // set some values:
  for (int i=1; i<10; i++) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9

  std::random_shuffle (myvector.begin(), myvector.end());

  // using default comparison (operator <):
  std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end());

  // using function as comp
  std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end(),myfunction);

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

输出:
myvector contains: 3 1 4 2 5 6 9 7 8

✥ 复杂度



一般来说,第一个和最后一个之间的距离是线性的: 比较元素,并可能交换(或移动)它们,直到元素被正确地重新排列。

⇄ 数据竞争


范围[first,last)中的对象被修改。

☂ 异常安全性



如果comp或swap(或move)或迭代器的操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。

🍄  另请参阅



sort 对范围内的元素进行排序(函数模板)
partial_sort 对范围内的元素进行部分排序(函数模板)
partition 对范围分区(函数模板)
find_if 在范围内查找元素(函数模板)

联系我们 免责声明 关于CandCplus 网站地图