国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

stable_sort()與sort()的用法區別

2019-11-11 01:42:49
字體:
來源:轉載
供稿:網友

關于stable_sort()和sort()的區別:

你發現有sort和stable_sort,還有 partition 和stable_partition, 感到奇怪吧。其中的區別是,帶有stable的函數可保證相等元素的原本相對次序在排序后保持不變。或許你會問,既然相等,你還管他相對位置呢,也分不清 楚誰是誰了?這里需要弄清楚一個問題,這里的相等,是指你提供的函數表示兩個元素相等,并不一定是一摸一樣的元素。

例如,如果你寫一個比較函數:

bool less_len(const string &str1, const string &str2){        return str1.length() < str2.length();}

此時,"apple" 和 "winter" 就是相等的,如果在"apple" 出現在"winter"前面,用帶stable的函數排序后,他們的次序一定不變,如果你使用的是不帶"stable"的函數排序,那么排序完 后,"Winter"有可能在"apple"的前面。

舉例說明:

#include <vector>#include <iostream>#include <algorithm>using namespace std;bool comp_as_int(double i, double j){	return (int(i)<int(j));}int main(){	double mydoubles[] = { 3.14, 1.41, 2.72, 4.67, 1.73, 1.32, 1.62, 2.58 };	vector<double> v;	vector<double>::iterator it;	v.assign(mydoubles, mydoubles + 8);	cout << "use default comparison:" << endl;	stable_sort(v.begin(), v.end());	for (it = v.begin(); it != v.end(); it++)		cout << *it << " ";	cout << endl;	cout << "use selfdefined comparison function comp_as_int():" << endl;	v.assign(mydoubles, mydoubles + 8);	//stable sort 是穩定排序。	stable_sort(v.begin(), v.end(), comp_as_int);	for (it = v.begin(); it != v.end(); it++)		cout << *it << " ";	cout << endl;		cout << "use comparison function comp_as_int():" << endl;	v.assign(mydoubles, mydoubles + 8);	//sort是不穩定排序。	sort(v.begin(), v.end(), comp_as_int);	for (it = v.begin(); it != v.end(); it++)		cout << *it << " ";	cout << endl;	cout << "if it is not sorted with stable_sort(), the sequence of all elements between 1 and 2 will be set randomly..." << endl;	int n;	cin >> n;	return 0;}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 治多县| 虞城县| 三穗县| 民县| 托克逊县| 汤阴县| 武宁县| 新巴尔虎左旗| 唐山市| 呼和浩特市| 改则县| 绥化市| 德保县| 中方县| 东阿县| 平和县| 葫芦岛市| 泽普县| 广州市| 察哈| 商丘市| 齐河县| 广河县| 柳江县| 怀远县| 探索| 上虞市| 垦利县| 如东县| 沧源| 湄潭县| 姚安县| 莎车县| 乌兰察布市| 宁安市| 卢氏县| 玉溪市| 邛崃市| 宁化县| 桂平市| 萨嘎县|