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晚上随便读了下,好的命名很重要,初步了解一下有这些算法吧,真要用了再查。

原文链接: https://www.cnblogs.com/fewolflion/p/12968641.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/350865

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午6:34
下一篇 2023年3月2日 上午6:34

相关推荐