sort的高深用法

2021-06-08 23:34:23 字數 1969 閱讀 1949

1、sort()

sort 對給定區間所有元素進行排序

stable_sort 對給定區間所有元素進行穩定排序

partial_sort 對給定區間所有元素部分排序

partial_sort_copy 對給定區間複製並排序

nth_element 找出給定區間的某個位置對應的元素

is_sorted 判斷乙個區間是否已經排好序

partition 使得符合某個條件的元素放在前面

stable_partition 相對穩定的使得符合某個條件的元素放在前面

語法描述為:

(1)sort(begin,end),表示乙個範圍,例如:

#include "stdafx.h"

#include

#include

using namespace std;

int _tmain(int argc, _tchar* argv)

,i;for(i=0;i<10;i++)

cout<

(2)sort(begin,end,compare)

一種是自己編寫乙個比較函式來實現,接著呼叫三個引數的sort:sort(begin,end,compare)就成了。

對於list容器,這個方法也適用,把compare作為sort的引數就可以了,即:sort(compare)。

1)自己編寫compare函式:

bool compare(int a,int b) //注意這裡的返回值型別,是bool型別,而不是qsort()函式那樣的int型別,而且引數更加簡化了

int _tmain(int argc, _tchar* argv)

,i;for(i=0;i<10;i++)

cout<

2)更進一步,讓這種操作更加能適應變化。也就是說,能給比較函式乙個引數,用來指示是按公升序還是按降序排,這回輪到函式物件出場了。

為了描述方便,我先定義乙個列舉型別enumcomp用來表示公升序和降序。很簡單:

enum enumcomp;

class compare

;bool operator () (int num1,int num2)}};

int main()

,i;for(i=0;i<10;i++)

cout<

3)其實對於這麼簡單的任務(型別支援「<」、「>」等比較運算子),完全沒必要自己寫乙個類出來。標準庫里已經有現成的了,就在functional裡,include進來就行了。functional提供了一堆基於模板的比較函式物件。它們是(看名字就知道意思了):equal_to、not_equal_to、greater、greater_equal、less、less_equal。對於這個問題來說,greater和less就足夠了,直接拿過來用:

公升序:sort(begin,end,less());

降序:sort(begin,end,greater()).

#include "stdafx.h"

#include

#include

#include

using namespace std;

int _tmain(int argc, _tchar* argv)

,i;for(i=0;i<10;i++)

cout<

sort(a,a+10,greater());

for(i=0;i<10;i++)

cout<

int main()

vec.push_back(a);

sort(vec.begin(),vec.end(),greater());

while(i

4)既然有迭代器,如果是string 就可以使用反向迭代器來完成逆序排列,程式如下:

#include "stdafx.h"

#include

#include

#include

using namespace std;

int main()

筆記 sort的用法

從別人 來的 是http bbs.ecust.edu.cn archiver tid 14302.html 因為在學,怕忘了,算作是筆記吧 sort的用法 按照給定的方案給區間中的元素排序。載入標頭檔案 include 函式原型 template void sort randomaccessiter...

sort函式的用法

sort函式的用法 做acm題的時候,排序是一種經常要用到的操作。如果每次都自己寫個冒泡之類的o n 2 排序,不但程式容易超時,而且浪費寶貴的比賽時間,還很有可能寫錯。stl裡面有個sort函式,可以直接對陣列排序,複雜度為n log2 n 使用這個函式,需要包含標頭檔案。這個函式可以傳兩個引數或...

sort函式的用法

sort函式包含在標頭檔案 include 中 1 預設的sort函式是按公升序排。sort a,a n 兩個引數分別為待排序陣列的首位址和尾位址,或者可以首尾指標。又如 vector iterator iter1 v.begin vector iterator iter2 v.begin sort...