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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

关于stable_sort()和sort()的区别:

發布時間:2024/4/18 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于stable_sort()和sort()的区别: 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

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

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

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

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

舉例說明:

#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; }

總結

以上是生活随笔為你收集整理的关于stable_sort()和sort()的区别:的全部內容,希望文章能夠幫你解決所遇到的問題。

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