STL 劃分與排序 3

2021-10-01 20:20:21 字數 1342 閱讀 5352

default (1)	

template void nth_element (randomaccessiterator first, randomaccessiterator nth,

randomaccessiterator last);

custom (2)

template void nth_element (randomaccessiterator first, randomaccessiterator nth,

randomaccessiterator last, compare comp);

功能:重排容器中的元素[first,last),nth所指的元素即為該位置出的有序元素,其前面的元素均滿足小於或大於該元素,但不一定有序;其後的元素均滿足大於或小於該元素,但不一定有序。

可實現快速確定第k個有序元素,或者輸出前k個有序元素(不要求順序輸出)

其原理也是基於快速排序的思想。

引數:first,nth,last均為迭代器,因此若nth=begin+5,實際上nth所指的元素是下標為5的元素(即第6個有序元素)

comp為二元函式,返回值為bool;

#include //std::cout

#include#include//vector

using namespace std;

bool myoperation(int a,int b)

//output the elements in the vector

random_shuffle(myvector.begin(),myvector.end());//打亂容器中元素順序

for(vector::iterator iter=myvector.begin();iter!=myvector.end();iter++)

cout<::iterator iter="myvector.begin();iter!=myvector.end();iter++)

cout<::iterator iter=" myvector.begin>

cout<::iterator iter="myvector.begin();iter!=myvector.end();iter++)

cout

for(vector::iterator iter=myvector.begin();iter!=myvector.end();iter++)

cout執行結果:

STL 排序與檢索

新增在標頭檔案algorithm中,使用方法如 sort start,end 排序方法 int a 5 sort a,a 5 這是最簡單的sort方法,使用預設的排序方法公升序排列 sort a,a 5,cmp cmp為bool函式名,是自定義規則比較函式 自定義的cmp函式 bool cmp in...

STL初步 排序與檢索

e.g.現有n個大理石,每個大理石上寫了乙個非負整數。首先把每個數從小到大排序,然後回答q個問題。每個問題問是否有乙個大理石寫著某個整數x。如果是,要回答在哪個大理石上寫著x。排序後的大理石從左到右編號為1 n。solution 先排序,後查詢 關於排序 sort使用陣列元素預設的大小比較運算子進行...

stl中的排序 3 find find if

直接上原始碼 template class inputiterator class t inputiterator find inputiterator first,inputiterator last,const t value template class inputiterator class...