某些算法会重排容器中元素的顺序,如std::sort。调用sort会重排输入序列中的元素,使之有序,它默认是利用元素类型的<运算符来实现排序的。也可以重载sort的默认排序,即通过sort的第三个参数,此参数是一个谓词(predicate)。

谓词是一个可调用的表达式,其返回结果是一个能用作条件的值,即返回一个bool类型的值。标准库算法所使用的谓词分为两类:一元谓词(unary predicate,只接受单一参数)和二元谓词(binary predicate,有两个参数)。接受谓词参数的算法对输入序列中的元素调用谓词。因此,元素类型必须能转换为谓词的参数类型。

接受一个二元谓词参数的sort版本用这个谓词代替<来比较元素。

std::sort:对给定区间所有元素进行排序。

std::stable_sort:对给定区间所有元素进行稳定排序,稳定排序算法能够维持相等元素的原有顺序。

std::partial_sort:对给定区间所有元素进行部分排序。

当容器中的元素是一些标准类型(如int、string)时,可以直接使用函数模板。但其元素是自定义类型或者需要按照其它方式排序时,需要自己来实现,有两种方法:一种是自己写比较函数,另一种是重载类型操作符”<”。std::sort/std::stable_sort/std::partial_sort中最后一个参数可以是函数指针类型或函数对象类型。

std::sort采用类似快速排序算法,复杂度为N*log2(N);std::stable_sort采用类似归并排序,复杂度为N*log2(N);std::partial_sort采用类似堆排序,复杂度为N*log(M)。但是在cplusplus中并没有说明每种sort采用的是具体哪种排序算法。

std::sort:Sort elements in range, Sorts the elements in the range [first,last) into ascending order. The elements are compared using operator< for the first version, and comp for the second. Equivalent elements are not guaranteed to keep their original relative order (see stable_sort).

std::stable_sort: Sort elements preserving order of equivalents. Sorts the elements in the range[first,last) into ascending order, like sort, but stable_sort preserves the relative order of the elements with equivalent values.

std::partial_sort:Partially sort elements in range. Rearranges the elements in the range [first,last), in such a way that the elements before middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining elements are left without any specific order.

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "sort1.hpp"
#include <iostream>
#include <algorithm> // std::sort
#include <functional> // std::greater
#include <vector>
#include <array>
#include <string>///
// reference: http://www.cplusplus.com/reference/algorithm/sort/
static bool myfunction(int i, int j) { return (i < j); }static struct myclass {bool operator() (int i, int j) { return (i < j); }
} myobject;int test_sort_1()
{int myints[] { 32, 71, 12, 45, 26, 80, 53, 33 };std::vector<int> myvector(myints, myints + 8);               // 32 71 12 45 26 80 53 33// using default comparison (operator <):std::sort(myvector.begin(), myvector.begin() + 4);           //(12 32 45 71)26 80 53 33// using function as compstd::sort(myvector.begin() + 4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)// using object as compstd::sort(myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)// print out content:std::cout << "myvector contains:";for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';myvector.assign(myints, myints + 8);std::sort(myvector.begin(), myvector.end(), std::greater<int>()); // descending is to use std::greater()std::cout << "myvector contains:";for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';// use std::sort to sort an array in C++11: std::begin/std::endstd::sort(std::begin(myints), std::end(myints));for (int i = 0; i < 8; ++i) {std::cout << " " << myints[i];}std::cout << "\n";return 0;
}/
// reference: https://www.codeproject.com/Articles/38381/STL-Sort-Comparison-Function
class Person_sort4 {
public:// default constructorPerson_sort4() : age(0) {}Person_sort4(int age, std::string name) {this->age = age; this->name = name;}bool operator<(const Person_sort4& rhs) { // define a member < operator for the Person classreturn this->age < rhs.age;}int age;std::string name;
};int test_sort_4()
{std::vector<Person_sort4> vecPerson;vecPerson.push_back(Person_sort4(24, "Calvin"));vecPerson.push_back(Person_sort4(30, "Benny"));vecPerson.push_back(Person_sort4(28, "Alison"));std::sort(vecPerson.begin(), vecPerson.end());for (size_t i = 0; i<vecPerson.size(); ++i)std::cout << vecPerson[i].age << ", " << vecPerson[i].name << std::endl;return 0;
}/
// reference: http://www.cplusplus.com/articles/NhA0RXSz/
struct Person_sort {// Left out making a constructor for simplicity's sake.std::string name;int age;std::string favoriteColor;
};// Sort Container by name function
static bool sortByName(const Person_sort &lhs, const Person_sort &rhs) { return lhs.name < rhs.name; }// Sort Container by age function
static bool sortByAge(const Person_sort &lhs, const Person_sort &rhs) { return lhs.age < rhs.age; }// Sort Container by favorite color
// We can just sort alphabetically and then it will group the color together.
static bool sortByColor(const Person_sort &lhs, const Person_sort &rhs) { return lhs.favoriteColor < rhs.favoriteColor; }// A global const variable to hold how many people to ask for input for.
const unsigned numberOfPeople = 2;int test_sort_2()
{using std::vector;using std::cout;using std::cin;using std::endl;using std::sort;using std::string;// Make a vector that holds 5 blank Person_sort Objectsvector<Person_sort> people { { "Tom", 23, "Red" }, {"Jim", 11, "Green"} };// This will ask for user input to populate the container// with 5 different indivuals.//for (vector<Person_sort>::size_type i = 0; i != numberOfPeople; ++i) {//  cout << "Person_sort #" << i + 1 << " name: ";// cin >> people[i].name;//  cout << "Person_sort #" << i + 1 << " age: ";//  cin >> people[i].age;//   cout << "Person_sort #" << i + 1 << " favorite color: ";//   cin >> people[i].favoriteColor;//}//cout << "\n\n";// Sort by namesort(people.begin(), people.end(), sortByName);for (Person_sort &n : people)cout << n.name << " ";cout << endl;// Sory by agesort(people.begin(), people.end(), sortByAge);for (Person_sort &n : people)cout << n.age << " ";cout << endl;// Sort by colorsort(people.begin(), people.end(), sortByColor);for (Person_sort &n : people)cout << n.favoriteColor << " ";cout << endl;return 0;
}/
// reference: http://en.cppreference.com/w/cpp/algorithm/sort
int test_sort_3()
{std::array<int, 10> s = { 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };// sort using the default operator<std::sort(s.begin(), s.end());for (auto a : s) {std::cout << a << " ";}std::cout << '\n';// sort using a standard library compare function objectstd::sort(s.begin(), s.end(), std::greater<int>());for (auto a : s) {std::cout << a << " ";}std::cout << '\n';// sort using a custom function objectstruct {bool operator()(int a, int b) const {return a < b;}} customLess;std::sort(s.begin(), s.end(), customLess);for (auto a : s) {std::cout << a << " ";}std::cout << '\n';// sort using a lambda expression std::sort(s.begin(), s.end(), [](int a, int b) {return b < a;});for (auto a : s) {std::cout << a << " ";}std::cout << '\n';return 0;
}/
// reference: http://www.cplusplus.com/reference/algorithm/stable_sort/
static bool compare_as_ints(double i, double j)
{return (int(i)<int(j));
}int test_stable_sort_1()
{double mydoubles[] { 3.14, 1.41, 2.72, 4.67, 1.73, 1.32, 1.62, 2.58 };std::vector<double> myvector;myvector.assign(mydoubles, mydoubles + 8);std::cout << "using default comparison:";std::stable_sort(myvector.begin(), myvector.end());for (std::vector<double>::iterator it = myvector.begin(); it != myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';myvector.assign(mydoubles, mydoubles + 8);std::cout << "using 'compare_as_ints' :";std::stable_sort(myvector.begin(), myvector.end(), compare_as_ints);for (std::vector<double>::iterator it = myvector.begin(); it != myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';return 0;
}/
// reference: http://en.cppreference.com/w/cpp/algorithm/stable_sort
struct Employee_sort {Employee_sort(int age, std::string name) : age(age), name(name) { }int age;std::string name;  // Does not particpate in comparisons
};static bool operator<(const Employee_sort &lhs, const Employee_sort &rhs)
{return lhs.age < rhs.age;
}int test_stable_sort_2()
{std::vector<Employee_sort> v = {Employee_sort(108, "Zaphod"),Employee_sort(32, "Arthur"),Employee_sort(108, "Ford"),};std::stable_sort(v.begin(), v.end());for (const Employee_sort &e : v) {std::cout << e.age << ", " << e.name << '\n';}return 0;
}// reference: http://www.cplusplus.com/reference/algorithm/partial_sort/
int test_partial_sort_1()
{int myints[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };std::vector<int> myvector(myints, myints + 9);// using default comparison (operator <):std::partial_sort(myvector.begin(), myvector.begin() + 5, myvector.end());// using function as compstd::partial_sort(myvector.begin(), myvector.begin() + 5, myvector.end(), myfunction);// print out content:std::cout << "myvector contains:";for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';return 0;
}

GitHub: https://github.com/fengbingchun/Messy_Test

C++中std::sort/std::stable_sort/std::partial_sort的区别及使用相关推荐

  1. python中sort和sorted区别_Python中的 sort 和 sorted的用法与区别

    今天在做一道题时,因为忘了Python中sort和sorted的用法与区别导致程序一直报错,找了好久才知道是使用方法错误的问题!现在就大致的归纳一下sort和sorted的用法与区别 1. sort: ...

  2. sort()、stable_sort()、partial_sort()、nth_element()、greater()、is_sorted()

    sort(a, a+5); // 默认从小到大,int数组的排序 sort(v.begin(), v.end()); // vector数组排序 sort中使用的是快排和插排 stable_sort( ...

  3. g++ -std=c++_在C ++ std库中使用sort()

    g++ -std=c++ 介绍 (Introduction) Hey there! Today we are going to discuss the sort() function in the s ...

  4. STL std::sort 源码分析

    转载自http://feihu.me/blog/2014/sgi-std-sort/ 最近在看sort源码,看到这篇博文很好,转发作为记录,转载侵权联系我删除 背景 在校期间,为了掌握这些排序算法,我 ...

  5. c语言中如何自定义sort,c – 如何重载自定义std :: sort比较函数?

    使用std :: sort时,如何重载我正在使用的自定义比较函数? #include #include #include #include class Misc { public: // Commen ...

  6. vector sort 出现异常处理--std::sort(_RanIt,_RanIt,_Pr)

    对于sort排序处理,网上一般使用 bool SortByValue( int v1,  int v2)//注意:本函数的参数的类型一定要与vector中元素的类型一致   { return v1 & ...

  7. 【STL源码阅读】std::sort(),十分钟了解msvc的stl的sort实现

    . 一份简化的代码(可读性较强) 看看std::sort()是怎么做的 打开vs,跳到sort的定义 在首先在algorithm中找到sort 可以看到这个sort是仅仅支持随机访问的迭代器 跳到 带 ...

  8. c语言ctype中替换查找字符,c – std :: ctype是否总是按“C”语言环境对字符进行分类?...

    该标准需要默认构造的std :: ctype< char>通过§22.4.1.3.3匹配最小"C"语言环境[facet.ctype.char.statics] / 1 ...

  9. C++演示std :: sort(),std :: reverse()的函数(附完整源码)

    @[TOC](C++演示std :: sort(),std :: reverse()的函数) C++演示std :: sort(),std :: reverse()的函数完整源码(定义,实现,main ...

最新文章

  1. OpenCV中minAreaRect()最小外接矩形 cvBoxPoints()计算矩形顶点 RotatedRect和CvBox2D详解
  2. FTP协议的命令的使用(转)
  3. 【SSH网上商城项目实战16】Hibernate的二级缓存处理首页的热门显示
  4. 蒸妙集团:大健康产业时代的弄潮儿,中国熏蒸行业的领跑者!
  5. Spring Cloud限流详解(附源码)
  6. python的窗口处理模块_Python tkinter模块弹出窗口及传值回到主窗口操作详解
  7. windows10小鹤双拼注册表
  8. 80后,天才程序员, Facebook 第一任 CTO,看看开挂的人生到底有多变态?
  9. LeetCode 1944. 队列中可以看到的人数(单调栈)
  10. android监听应用服务,Android应用中Back键的监听及处理实例
  11. apache shiro版本查看_深入学习SpringBoot(四):springboot整合shiro
  12. 【AI视野·今日NLP 自然语言处理论文速览 第一期】Fri, 4 Jun 2021
  13. Stackoverflow 年度报告 2020:开发者最喜爱的数据库是什么?
  14. mysql 内置存储过程_mysql 内置存储过程
  15. js运行机制详解:event loop
  16. rpath失效是怎么回事
  17. iOS 开发比较实用的框架总结(上)
  18. 用 DocFetcher 全文搜索
  19. 新手建站推广完美教程(重点推荐)
  20. 绑定薇娅李佳琦,不灵了

热门文章

  1. 直方图均衡化opencv(彩色、灰度图)
  2. 读后感与机翻《从视频中推断力量和学习人类效用》
  3. 树莓派的Raspbian Stretch with desktop和Ubuntu Mate(废弃)
  4. 1.一步一步移植ucos到stm32f103开发版(修订版)
  5. HDU - 3078 Network 倍增LCA
  6. 【机器学习入门】(10) 特征工程:特征抽取,字典特征抽取、文本特征抽取,附完整python代码
  7. 在CentOS 7.7 x86_64上安装python3的selenium 3模块实录
  8. 在Ubuntu 14.04 64bit上安装CHM阅读器KchmViewer 5.3
  9. Rocksdb 通过posix_advise 让内核减少在page_cache的预读
  10. 一、nginx 安装