【C++11】C++11新增的便利算法[1] all_of、any_of 和 none_of

本文选自:祁宇. 深刻应用C++11:代码优化与工程级应用. 北京:机械工业出版社,2015.5ios

有改动。算法

 

算法库新增了3个用于判断的算法 all_of、any_of 和 none_of:优化

template<class _InIt, class _Pr>
bool all_of(_InIt _First, _InIt _Last, _Pr _Pred);

template<class _InIt, class _Pr>
bool none_of(_InIt _First, _InIt _Last, _Pr _Pred);

template<class _InIt, class _Pr>
bool any_of(_InIt _First, _InIt _Last, _Pr _Pred);

其中:spa

all_of 检查区间 [ _First, _Last ) 中是否全部元素都知足一元判断式 _Pr。code

any_of 检查区间 [ _First, _Last ) 中是否存在一个元素知足一元判断式 _Pr。it

none_of 检查区间 [ _First, _Last ) 中是否全部元素都知足一元判断式 _Pr。io

 

下面是它们的例子:ast

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

auto IsOdd(int n) -> bool
{
    return n % 2 != 0;
}

int main()
{
    std::vector<int> v0{ 1,3,5,7,9 };
    std::vector<int> v1{ 2,3,6,7,89,100 };
    std::vector<int> v2{ 2,4,46,80,8 };

    if (std::all_of(v0.begin(), v0.end(), ::IsOdd))
    {
        std::cout << "都是奇数。" << std::endl;
    }

    if (std::any_of(v1.begin(), v1.end(), ::IsOdd))
    {
        std::cout << "有奇数。" << std::endl;
    }

    if (std::none_of(v2.begin(), v2.end(), ::IsOdd))
    {
        std::cout << "没有奇数。" << std::endl;
    }

    return 0;
}
相关文章
相关标签/搜索