C++ nth_element函数用法学习

本文介绍了C++ STL中的nth_element函数,该函数能够将容器中的元素按指定位置划分,使得该位置左侧的元素不大于该位置的元素,右侧的元素不小于该位置的元素。文章通过示例代码详细展示了nth_element函数的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

nth_element() 需要头文件<algorithm>。典型参数表为

nth_element(RandomIt first, RandomIt nth,  RandomIt last, Compare comp = less);

nth_element的作用就是根据nth这个参数,把容器内的元素分为2组,nth之前的都比它小,nth之后的都比它大。类似partition算法。

注意:

  1. nth之前和之后的元素都不保证排序。

  2. nth_element()所支持的容器中只有array, vector和deque这3种可用于随机访问的容器。别的容器不支持随机访问,所以不能用nth_element。

  3. C++ STL里面,deque支持随机访问,stack和queue都不支持随机访问。

下面是典型用法:

 #include <iostream>
 #include <algorithm>
 #include <vector>
 ​
 using namespace std;
 ​
 bool comp1(int a, int b) {
     return a > b;
 }
 ​
 class comp2{
 public:
     bool operator() (int a, int b) {
         return a > b;
     }
 } cmp2;
 ​
 int main() {
     vector<int> vec{7, 1, 2, 6, 100};
     nth_element(vec.begin(), vec.begin() + 2, vec.end());
     cout << "after first nth_element" << endl;
     for (auto iter = vec.begin(); iter != vec.end(); iter++) {
         cout << *iter << endl;
     }
     nth_element(vec.begin(), vec.begin() + 2, vec.end(), comp1);
     cout << "after second nth_element" << endl;
     for (auto iter = vec.begin(); iter != vec.end(); iter++) {
         cout << *iter << endl;
     }
 ​
     nth_element(vec.begin(), vec.begin() + 3, vec.end(), cmp2);
     cout << "after third nth_element" << endl;
     for (auto iter = vec.begin(); iter != vec.end(); iter++) {
         cout << *iter << endl;
     }
     return 0;
 }

其输出为:

 after first nth_element
 2
 1
 6
 7
 100
 after second nth_element
 100
 7
 6
 2
 1
 after third nth_element
 6
 7
 100
 2
 ​

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值