C++标准库中的std::nth_leement

发布时间 2023-03-29 13:13:08作者: weihao_ysgs

std中的nth_element

  • 默认求的是数组中第 n 小的元素
  • 可以通过参数传入,求第 n 大的元素

示例代码

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char const *argv[])
{
  vector<int> array1 = {2, 3, -1, 5, 0, 11, 1};
  std::for_each(array1.begin(), array1.end(),
                [](const int &value) { std::cout << value << "\t"; });
  std::cout << std::endl;
  std::vector<int>::iterator mid_value = array1.begin() + 2;
  std::nth_element(array1.begin(), mid_value, array1.end());
  std::cout << "\nnth value: " << *mid_value << std::endl;

  std::for_each(array1.begin(), array1.end(),
                [mid_value](const int &value) { std::cout << value << "\t"; });
  std::cout << std::endl;
  const int nth_ele = 2;
  vector<int> array2 = {2, 3, -1, 5, 0, 11, 1};
  std::vector<int>::iterator nthvalue = array2.begin() + nth_ele;
  std::nth_element(array2.begin(), nthvalue, array2.end(),
                   [](int a, int b) -> bool { return a > b; });
  std::cout << "nth value: " << *nthvalue << std::endl;
  std::for_each(array2.begin(), array2.end(),
                [](const int &value) { std::cout << value << "\t"; });
  std::cout << endl;
  return 0;
}

输出:

2       3       -1      5       0       11      1
// 原数组中第 2 小的元素,注意这里有第 0 小的元素
nth value: 1
0       -1      1       2       3       11      5
// 原数组中第 2 大的元素,注意这里有第 0 大的元素
nth value: 3
11      5       3       -1      0       2       1