头文件:
#include <algorithm>
//用默认的比较函数进行对比 template< class RandomIt > void sort( RandomIt first, RandomIt last ); //指定比较函数为comp template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp );
参数:
first, last - 要排序的元素范围
comp - 比较函数对象(即满足比较 (Compare) 概念的对象),若第一参数小于(即先序于)第二参数则返回 ?true 。
比较函数的签名应等价于如下:
bool cmp(const Type1 &a, const Type2 &b);
虽然签名不必有 const & ,函数也不能修改传递给它的对象,而且必须接受(可为 const 的)类型 Type1 与 Type2 的值,无关乎值类别(从而不允许 Type1 & ,亦不允许 Type1 ,除非 Type1 的移动等价于复制 (C++11 起))。
类型 Type1 与 Type2 必须使得 RandomIt 类型的对象能在解引用后隐式转换到这两个类型。
用法:以不降序排序范围 [first, last)
中的元素,不保证维持相等元素的顺序。
若对于任何指向序列的迭代器 it
与任何使得 it + n
为指向序列元素的合法迭代器的非负整数 n
, comp(*(it + n), *it) 求值为 false
,则称序列相对于 comp
已排序。
operator<
比较元素。comp
比较元素。array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; // 用默认的 operator< 排序 std::sort(s.begin(), s.end()); for (auto a : s) { std::cout << a << " "; } std::cout << ‘\n‘; // 用自定义函数对象排序 struct { 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 << " "; }
原文:https://www.cnblogs.com/jinyanzzang/p/14106817.html