#include <algorithm>
#include <vector>
#include <functional>
// 自定义的函数
bool my_greater(int& a, int& b)
{
return a > b;
}
int main(int argc, char** argv)
{
std::vector<int> vec;
vec.push_back(5);
vec.push_back(3);
vec.push_back(4);
vec.push_back(1);
vec.push_back(2);
vec.push_back(0);
for (auto &i : vec)
{
printf("%d,", i);
}
puts("");
// 使用默认行为进行比较(默认就是使用小于运算符)
std::sort(vec.begin(), vec.end());
for (auto& i : vec)
{
printf("%d,", i);
}
puts("");
// 使用大于运算符进行比较
std::sort(vec.begin(), vec.end(), std::greater<int>());
for (auto& i : vec)
{
printf("%d,", i);
}
puts("");
// 或者手工指定小于运算符
std::sort(vec.begin(), vec.end(), std::less<int>());
for (auto& i : vec)
{
printf("%d,", i);
}
puts("");
// 或者可以自己定义一个大于比较函数进行比较
std::sort(vec.begin(), vec.end(), my_greater);
for (auto& i : vec)
{
printf("%d,", i);
}
puts("");
// 也可以写成lamda表达式
auto fun = [](int& a, int& b){ return a < b; };
std::sort(vec.begin(), vec.end(), fun);
for (auto& i : vec)
{
printf("%d,", i);
}
puts("");
// 或着
std::sort(vec.begin(), vec.end(), [](int& a, int& b){ return a > b; });
for (auto& i : vec)
{
printf("%d,", i);
}
puts("");
getchar();
return 0;
}
C++之std::sort排序
最新推荐文章于 2024-04-29 11:56:38 发布