C++排序之stable_sort()的方法
2017-02-06 13:23
477 查看
stable_sort()可以对vector的某个成员进行排序,而且可保证相等元素的原本相对次序在排序后保持不变。
下面是该函数的实现方法代码:
其结果如下:
输入:98 34 6 3 8 1 100 45 66 88 202
输出:
Index Value:
6 1
4 3
3 6
5 8
2 34
8 45
9 66
10 88
1 98
7 100
11 202
下面是该函数的实现方法代码:
#include <iostream> #include<math.h> #include <string> #include <vector> #include <iterator> #include <algorithm> 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> vtNode; vtNode.clear(); Node tmp; int idx = 0, num; while(cin >> num && num) { ++idx; tmp.value = num; tmp.index = idx; vtNode.push_back(tmp); } stable_sort(vtNode.begin(), vtNode.end(), myCmp); cout << "Index\tValue:" << endl; vector<Node>::iterator pos; for(pos = vtNode.begin(); pos != vtNode.end(); ++pos) { cout << pos->index << "\t" << pos->value << endl; } return 0; }
其结果如下:
输入:98 34 6 3 8 1 100 45 66 88 202
输出:
Index Value:
6 1
4 3
3 6
5 8
2 34
8 45
9 66
10 88
1 98
7 100
11 202
相关文章推荐
- c、c++排序函数qsort、stable_sort
- C++ 排序函数 sort(),qsort()的使用方法
- C++ 排序函数 sort(),qsort()的使用方法
- c++中sort的vector中结构体排序的两种方法说明
- C++ 排序函数 sort(),qsort()的使用方法
- C++排序之sort()的方法
- C++ 排序函数 sort(),qsort()的使用方法
- C++ 关于STL中sort()对struct排序的方法
- C++ 排序函数 sort(),qsort()的使用方法
- 实战c++中的vector系列--使用sort算法对vector进行排序(对vector<string>排序、使用稳定的排序std::stable_sort())
- 关于C++中vector和set使用sort方法进行排序
- 实战c++中的vector系列--使用sort算法对vector进行排序(对vector<string>排序、使用稳定的排序std::stable_sort())
- C++ 排序函数 sort(),qsort()的使用方法
- C++ 排序函数 sort(),qsort()的使用方法
- C++语法基础--泛型算法(generic algorithm)--对容器排序的算法sort(),stable_sort(),unique()
- C++ STL中sort方法对自定义类的排序
- 常见排序的原理和C++实现(一)——STL库中sort的使用方法
- 一般的排序方法C++
- Collections 类的sort 方法排序
- HDOJ 1106 排序 [stable_sort]