C++ 标准模板库 ( STL , Standard Template Library ) 中 提供 了 sort 算法 函数 , 该函数定义在
sort 算法 用于 对容器中的元素排序 , 该算法效率很高 , 可以 对给定 迭代器范围 内的元素进行排序 , 并且可以 根据用户指定的 比较函数 来定义排序的顺序 ;
用户指定的 比较函数 是一个 二元谓词 ;
std::sort 算法 默认排序规则 的 函数原型如下 :
template< class RandomIt >
void sort( RandomIt first, RandomIt last );
std::sort 算法 自定义排序规则 的 函数原型如下 :
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
C++ 标准模板库 ( STL , Standard Template Library ) 中 提供 了 greater
该 函数对象 主要用于STL算法 中 控制排序顺序 , 搜索条件 等场景 ;
greater
greater
代码示例 :
#include "iostream"
using namespace std;
#include
#include
#include "functional"
int main() {
// 创建一个 set 集合容器
vector<int> myVector;
// 向容器中插入元素
myVector.push_back(9);
myVector.push_back(5);
myVector.push_back(2);
myVector.push_back(7);
// 向 foreach 循环中传入 Lambda 表达式
for_each(myVector.begin(), myVector.end(), [](int a) {
std::cout << a << " ";
});
cout << endl;
// 将 myVector 容器中的元素按照从大到小的顺序排列
sort(myVector.begin(), myVector.end(), greater<int>());
// 向 foreach 循环中传入 Lambda 表达式
for_each(myVector.begin(), myVector.end(), [](int a) {
std::cout << a << " ";
});
cout << endl;
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};
执行结果 :
9 5 2 7
9 7 5 2
Press any key to continue . . .