sort演算法函式排序示例

2021-07-15 20:31:03 字數 1078 閱讀 9496

#include #include #include #include using namespace std;

// 自己定義的比較函式,sort預設按照運算子'<'的關係從小到大進行排序。

// 通過定義自己的比較函式,可以定義「自己想要的《關係",並在滿足這種關係時,返回true。

// 比較函式的輸入引數為待比較的物件。

bool comp(const string str1, const string str2)

return false;

}int main()

; sort(arraytest1, arraytest1 + 5);

for (int i = 0; i < 5; i++)

// 不自己定義比較函式,對vector進行排序的情況

vectortest2;

test2.push_back(10);

test2.push_back(8);

test2.push_back(7);

test2.push_back(11);

test2.push_back(1);

sort(test2.begin(), test2.end());

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

// 自己定義比較函式,對陣列或vector進行排序

vectortest3;

test3.push_back("dawei");

test3.push_back("huangxiaoming");

test3.push_back("zhuzhihao");

test3.push_back("woshinidie");

sort(test3.begin(), test3.begin() + test3.size(), comp);

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

return 0;

}

sort排序函式

所以自己總結了一下,首先看sort函式見下表 函式名 功能描述 sort 對給定區間所有元素進行排序 stable sort 對給定區間所有元素進行穩定排序 partial sort 對給定區間所有元素部分排序 partial sort copy 對給定區間複製並排序 nth element 找出給...

sort 排序函式

需要標頭檔案 語法描述 sort begin,end,cmp cmp引數可以沒有,如果沒有預設公升序排序。sort函式使用例項 include include includeusing namespace std int main sort a,a 5 for int i 0 i 5 i cout ...

sort 排序函式

include include 因為用了sort 函式 include 因為用了greater using namespace std void main int i int len sizeof a sizeof int 這裡切記要除以sizeof int sort a a len,greater...