STL stable_sort 稳定排序
2012-11-27 13:09
288 查看
STL stable_sort 稳定排序 - woaidongmao - C++博客
stable_sort()内部由归并排序来实现。
//Coded by 代码疯子
//http://www.programlife.net/
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
typedef struct TagNode
{
int value;
int index;
}Node;
bool myCmp(const Node& a, const Node& b)
{
return a.value < b.value;
}
int main(int argc, char **argv)
{
vector<Node> coll;
Node tmp;
int idx = 0, num;
while(cin >> num && num)
{
++idx;
tmp.value = num;
tmp.index = idx;
coll.push_back(tmp);
}
stable_sort(coll.begin(), coll.end(), myCmp);
cout << "Index\tValue:" << endl;
vector<Node>::iterator pos;
for(pos = coll.begin(); pos != coll.end(); ++pos)
{
cout << pos->index << "\t" << pos->value << endl;
}
return 0;
}
程序的运行结果如下图所示,可以看到,对于元素值相同的元素,索引小的在前面,稳定排序就是这么一个效果。
STL stable_sort 稳定排序
所谓稳定排序,是指对一个序列进行排序之后,如果两个元素的值相等,则原来乱序时在前面的元素现在(排好序之后)仍然排在前面。STL中提供stable_sort()函数来让我们进行稳定排序。为了更好的说明稳定排序的效果,我们定义了一个结构体元素,一个value成员和一个index成员,前者表示元素的值,后者表示乱序时的索引。stable_sort()内部由归并排序来实现。
//Coded by 代码疯子
//http://www.programlife.net/
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
typedef struct TagNode
{
int value;
int index;
}Node;
bool myCmp(const Node& a, const Node& b)
{
return a.value < b.value;
}
int main(int argc, char **argv)
{
vector<Node> coll;
Node tmp;
int idx = 0, num;
while(cin >> num && num)
{
++idx;
tmp.value = num;
tmp.index = idx;
coll.push_back(tmp);
}
stable_sort(coll.begin(), coll.end(), myCmp);
cout << "Index\tValue:" << endl;
vector<Node>::iterator pos;
for(pos = coll.begin(); pos != coll.end(); ++pos)
{
cout << pos->index << "\t" << pos->value << endl;
}
return 0;
}
程序的运行结果如下图所示,可以看到,对于元素值相同的元素,索引小的在前面,稳定排序就是这么一个效果。
相关文章推荐
- STL stable_sort 稳定排序
- 【STL】stable_sort !!!
- 【stable_sort稳定排序】
- STL中的排序算法 sort stable_sort patition_sort等
- STL中的排序算法 sort stable_sort patition_sort等
- STL之stable_sort与sort
- STL 之 stable_sort 将牌从大到小排序
- Aizu ALDS1_2_C Stable Sort(稳定排序)
- stl-stable_sort源码学习笔记
- STL中的排序算法 sort stable_sort patition_sort等
- 如何使用stable_sort() algorithm? (C/C++) (STL)
- stl-stable_sort源码学习笔记
- hdu 1872 稳定排序(stable_sort)
- STL_算法(27)_对所有元素排序sort(b, e) sort(b, e, p) stable_sort(b, e) stable_sort(b, e, p)
- STL_算法_对全部元素排序(sort、stable_sort)
- STL_算法_对所有元素排序(sort、stable_sort)
- stl-stable_sort源码学习笔记
- STL算法之sort和stable_sort
- STL中的排序算法 sort stable_sort patition_sort等
- stable_sort稳定排序