日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ nth_element 介绍

發布時間:2023/12/14 c/c++ 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 4

4、 時間復雜度

O(n)O(n)O(n)

參考資料

https://www.cplusplus.com/reference/algorithm/nth_element/

總結

以上是生活随笔為你收集整理的C++ nth_element 介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。