[65] sorting in C++ 排序

这里的重点是sort函数。

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

int main()
{
    std::vector<int> values = { 3,5,2,4,1 };
    //升序
    //std::sort(values.begin(), values.end());

    //写lambda表达式
    std::sort(values.begin(), values.end(), [] (int a,int b)
        {
            return a > b;
        });

    std::cin.get();
}

sort函数的第三个参数,要返回一个bool类型,它实际上是这样的

[](int a,int b){} 如果我们给俩个数a,b,那么去规定谁在前,谁在后输出,如果是输出true,意思是a在前,如果是false,意思是b在前。

所以我们可以这样写

return a<b;

那么,就是升序,更换为>,则是降序。

我们可以去验证一下

#include <functional>

int main()
{
    std::vector<int> values = { 3,5,2,4,1 };
    //升序
    //std::sort(values.begin(), values.end());

    //写lambda表达式
    std::sort(values.begin(), values.end(), [] (int a,int b)
        {
            if (a == 1)
                return false;
            if (b == 1)
                return true;
            return a < b;
        });

      for (int value : values)
          std::cout << value << std::endl;

    std::cin.get();
}

这样的判断条件,在总体升序的情况下,1会被挪到最后。

猜你喜欢

转载自www.cnblogs.com/EvansPudding/p/12543232.html