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

📅  最后修改于: 2021-06-01 02:22:51             🧑  作者: Mango

C++ Boost库中one_of()函数位于标题“ boost / algorithm / cxx11 / one_of.hpp”下,该标题将测试序列的元素,如果恰好一个元素共享给定的属性,则返回true。它接受一个序列和一个谓词,如果该谓词恰好对序列中的一个给定元素返回true,则返回true。

语法

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

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

返回值:如果给定谓词恰好在序列的元素之一上,则该函数返回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::one_of(c, isOdd);
  
    // Condition to check
    if (ans == 1)
        cout << "Exactly one element is odd";
    else
        cout << "Exactly one element is not odd";
    return 0;
}
输出:
Exactly one element is not 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 oneLessThanSeven(int i)
{
    return i < 7;
}
  
// Drivers code
int main()
{
  
    // Declares the sequence
    int a[] = { 1, 9, 10, 8 };
  
    // Run the function with first syntax
    bool ans
        = boost::algorithm::one_of(a, a + 4,
                                   oneLessThanSeven);
  
    // Condition to check
    if (ans == 1)
        cout << "Exactly one element is less than 7";
    else
        cout << "Exactly one element is not less than 7";
    return 0;
}
输出:
Exactly one element is less than 7

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

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”