C++ nth_element(STL nth_element)排序算法详解

  • 内容
  • 评论
  • 相关

nth_element() 算法和 partial_sort() 不同。应用的范围由它的第一个和第三个参数指定。第二个参数是一个指向第 n 个元素的迭代器。如果这个范围内的元素是完全有序的,nth_dement() 的执行会导致第 n 个元素被放置在适当的位置。这个范围内,在第 n 个元素之前的元素都小于第 n 个元素,而且它后面的每个元素都会比它大。算法默认用 < 运算符来生成这个结果。

下面是一个使用 nth_elemen() 的示例:

std::vector<int> numbers {22, 7, 93, 45, 19, 56, 88, 12, 8, 7, 15, 10};
size_t count {5}; // Index of nth element
std::nth_element(std::begin(numbers), std::begin(numbers) + count, std::end(numbers));

这里的第 n 个元素是 numbers 容器的第 16 个元素,对应于 numbers[5],图 1 展示了它的工作方式。



图 1 nth_element() 算法的操作

本文标题:C++ nth_element(STL nth_element)排序算法详解

本文地址:http://www.hosteonscn.com/2965.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注