• C++11:26C++11新增的便利算法


    26、C++11新增的便利算法

    0、课前秀

    1、all_of、any_of和none_of算法

    • all_of检查区间[first,last)中是否所有的元素都满足一元判断式p,所有的元素都满足条件返回true,否则返回false。
    • any_of检查区间[first,last)中是否至少有一个元素都满足一元判断式p,只要有一个元素满足条件返回true,否则返回false。
    • none_of检查区间[first,last)中是否所有的元素都不满足一元判断式p,所有的元素都不满足条件返回true,否则返回false。
    • 例子
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> v = {1,3,5,7,9};
        auto isEven = [](int i){return i % 2 != 0;}
        bool isallOdd = std::allof(v.begin(), v.end(),isEven);
        if(isallOdd)
            cout << "all is odd" << endl;
        
        bool isNoneEven = std::noneof(v.begin(), v.end(),isEven);
        if(isNoneEven)
            cout << "none is even" << endl;
        
        vector<int> v1 = {1,3,5,7,8,9};
        bool anyof = std::any_of(v.begin(), v.end(),isEven);
        if(anyof)
            cout << "at least one is even" << endl;
    }
    
    /*
    输出结果:
    */
    

    2、find_if_not算法

    3、copy_if算法

    4、iota算法

    • iota算法,用来方便地生成有序序列。
    • iota的基本用法.cpp
    #include <numeric>
    #include <array>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    int main()
    {
        vector<int> v(4);
        //循环遍历赋值来初始化数组
        /*
        for(int i=1;i<=4;i++)
        {
            v.push_back(i);
        }
        */
        
        //直接通过iota初始化数组,更简洁
        std::iota(v.begin(), v.end(),1);
        for(auto n : v)
        {
            cout << n << ' ';
        }
        cout << endl;
        
        std::array<int,4>array;
        std::iota(array.begin(), array.end(), 1);
        for(auto n: array)
        {
            cout << n << ' ';
        }
        std::cout << endl;
    }
    /*
    输出结果:
    1 2 3 4
    1 2 3 4
    */
    

    5、minmax_elemen算法

    • 这样不用分别调用max_element和max_element算法了。minmax_element会将最小值和最大值的迭代器放到一个pair中返回。
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    int main()
    {
        //your code goes here
        vector<int> v = {1,2,5,7,9,4};
        auto result = minmax_element(v.begin(), v.end());
        
        cout<<*result.first<<" "<<*result.second<<endl;
        return 0;
    }
    

    6、is_sorted和is_sorted_until算法

    • is_sorted_until则用来返回序列中前面已经排好序的部分序列。

    ReadMe

    • 20200526晚上随便读了下,好的命名很重要,初步了解一下有这些算法吧,真要用了再查。
  • 相关阅读:
    二级缓存配置和原理
    延迟加载
    proxy和no-proxy的策略取值的区别
    inverse理解
    Java Spring mvc 操作 Redis 及 Redis 集群
    章节6 关联映射 (转载)
    8.28笔记
    8.26函数相关练习
    8.26 课堂自由笔记 还有考皮的老师笔录
    大话设计模式1.0.2-----策略模式 单一职责原则 和 开放-封闭原则
  • 原文地址:https://www.cnblogs.com/fewolflion/p/12968641.html
Copyright © 2020-2023  润新知