stable_sort()与sort()的用法区别
来源:互联网 发布:unity3d 2d碰撞检测 编辑:程序博客网 时间:2024/05/22 03:08
关于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;}
0 0
- stable_sort()与sort()的用法区别
- stable_sort()与sort()的用法区别
- stable_sort()与sort()的用法区别
- 关于sort与stable_sort的初级用法
- stable_sort() 和 sort() 的区别
- stable_sort()和sort()的区别
- sort和stable_sort的区别和联系
- sort()和stable_sort()用法
- C++ sort() 与stable_sort()
- C ++ sort()与stable_sort()
- sort与stable_sort
- sort与stable_sort
- C ++ sort()与stable_sort()
- C++中sort函数和 stable_sort函数的区别
- c++中stable_sort 和sort()的区别及应用
- STL之stable_sort与sort
- stable_sort()方法 与 sort()方法
- C++中std::sort/std::stable_sort/std::partial_sort的区别及使用
- OpenGL学习笔记4_0(基本词汇和转换定义)
- 编写函数int stat(int a[],int n,int c[][2])
- ES6学习笔记
- 如何对栈进行简单的初级操作
- [SinGuLaRiTy-1002] Miller Rabin Prime Judge 米勒·罗宾素数判定法
- stable_sort()与sort()的用法区别
- iOS APP 上架证书打包
- 详解Shell脚本实现iOS自动化编译打包提交
- LVS工作原理以及工作模式简介
- poj1018
- Titan Graph DataBase 研究 (三)----Java API使用 上
- 监听浏览器后退按钮
- LVS集群中的IP负载均衡技术
- MongoDB Java Driver