C++ nth_element 介绍
1、功能
使用默認比較器
template <class RandomAccessIterator>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last);
自定義元素比較器
template <class RandomAccessIterator, class Compare>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,RandomAccessIterator last, Compare comp);
重新排列[first,last),使第n個位置的元素是排序序列中該位置的元素。
剩下的其他元素沒有任何特定的順序,除了第n個元素之前的元素都不大于它,第n個元素之后的元素都不小于它。 第一個版本使用<操作符比較元素,第二個版本使用comp操作符比較元素。
總的來說比較像用快排找第n大的元素。
2、參數
1. first,last
表明排序區間
2. nth
所需的第nth大元素的迭代器
3. comp
接受范圍內的兩個元素作為參數,并返回可轉換為bool類型的值的雙參數函數。
3、示例
#include <iostream> // std::cout #include <string> // std::string, std::stoi #include <vector> #include<algorithm> using namespace std; struct node {int i,j; }; bool cmp(node a, node b) {//先按照i的大小從大到小排if(a.i != b.i) return a.i > b.i;//如果i一樣就按照j的大小從大到小排else return a.j > b.j; } int main () {vector<int> v_int;vector<node> v_node;int a_int[10];for(int i = 0; i < 10; i ++){v_int.push_back(i);a_int[i] = i;for(int j = 0; j < 10; j ++){v_node.push_back({i,j});}}nth_element(v_int.begin(),v_int.begin() + 5, v_int.end());nth_element(v_node.begin(),v_node.begin() + 5, v_node.end(),cmp);nth_element(a_int,a_int + 5, a_int + 10);cout << "v_int :"<< *(v_int.begin() + 5) << endl;cout << "a_int :"<< *(a_int + 5) << endl;cout << "v_node :"<< v_node[5].i << " " << v_node[5].j << endl;return 0; } 輸出 v_int :5 a_int :5 v_node :9 44、 時間復雜度
O(n)O(n)O(n)
參考資料
https://www.cplusplus.com/reference/algorithm/nth_element/
總結
以上是生活随笔為你收集整理的C++ nth_element 介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联通鸿蒙卡怎么样,联通腾讯大王卡对比百度
- 下一篇: 一点透视,二点透视,三点透视的理解