📜  C++库中的boost :: algorithm :: any_of()

📅  最后修改于: 2021-05-30 12:10:11             🧑  作者: Mango

C++ Boost库中any_of()函数位于标头‘boost / algorithm / cxx11 / any_of.hpp’下,该标头测试序列中的元素,如果任何元素共享给定的属性,则返回true。它接受一个序列和一个谓词,如果该谓词对序列中的任何给定元素返回true,则返回true。

语法

参数:该函数接受如下所述的参数:

  • first :它指定输入迭代器到序列中的初始位置。
  • second :它指定输入迭代器到序列中的最终位置。
  • p :它指定一个一元谓词函数,该函数接受一个元素并返回bool。
  • R :这是完整的序列。

返回值:如果给定谓词在序列的任何元素上为true,则该函数返回true,否则返回false。

下面是上述方法的实现:

计划1

// C++ program to implement the
// above mentioned function
  
#include 
#include 
using namespace std;
// using boost::algorithm;
  
// Predicate function to check if
// the element is odd or not
bool isOdd(int i)
{
    return i % 2 == 1;
}
  
// Drivers code
int main()
{
  
    // Declares the sequence
    int c[] = { 1, 2, 3 };
  
    // Run the function with second syntax
    bool ans = boost::algorithm::any_of(c, isOdd);
  
    // Condition to check
    if (ans == 1)
        cout << "at least one element is odd";
    else
        cout << "all elements are even";
    return 0;
}
输出:
at least one element is odd

计划2

// C++ program to implement the
// above mentioned function
  
#include 
#include 
using namespace std;
// using boost::algorithm;
  
// Predicate function to check if
// the elements are less than 7 or not
bool anyLessThanSeven(int i)
{
    return i < 7;
}
  
// Drivers code
int main()
{
  
    // Declares the sequence
    int a[] = { 1, 2, 10, 8 };
  
    // Run the function with first syntax
    bool ans
        = boost::algorithm::any_of(a, a + 4,
                                   anyLessThanSeven);
  
    // Condition to check
    if (ans == 1)
        cout << "at least one element is less than 7";
    else
        cout << "all elements are not less than 7";
    return 0;
}
输出:
at least one element is less than 7

参考:https://www.boost.org/doc/libs/1_70_0/libs/algorithm/doc/html/the_boost_algorithm_library/CXX11/any_of.html

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”