Boost 学习之算法篇 one_of 与 one_of_equal

来源:互联网 发布:nginx ip转发 编辑:程序博客网 时间:2024/05/29 17:54
one_of
头文件 'boost/algorithm/cxx11/one_of.hpp' 包含4个名为one_of的常用算法.
该算法测试序列中的所有参数,假如测试这些元素发现其中只有一个含有特别的属性,则返回true.
常用的one_of 函数带有一个参数序列以及一个候选值。假如用候选值与参数序列中所有元素只有一个返回true,则该函数将返回true。
常用的one_of_equal 函数带一个参数序列和一个值。假如参数序列中只有一个值和传入的值比较相同,则返回true。

上述两个函数都有两种调用方式:第一种方式带了一对迭代器,用来标记参数范围;第二种方式方式带了一个用Boost.Range转换后的范围参数。

请特别注意上述关键字:只有一个!

原文链接:http://www.boost.org/doc/libs/1_60_0/libs/algorithm/doc/html/the_boost_algorithm_library/CXX11/one_of.html

官方API

namespace boost { namespace algorithm {template<typename InputIterator, typename Predicate>bool one_of ( InputIterator first, InputIterator last, Predicate p );template<typename Range, typename Predicate>bool one_of ( const Range &r, Predicate p );}}

namespace boost { namespace algorithm {template<typename InputIterator, typename V>bool one_of_equal ( InputIterator first, InputIterator last, V const &val );template<typename Range, typename V>bool one_of_equal ( const Range &r, V const &val );}}

举例详解]

#include <boost/algorithm/cxx11/one_of.hpp>#include <iostream>#include <vector>using namespace boost::algorithm;bool isOdd(int i){  return i % 2 == 1;}bool lessThan10(int i){ return i < 10;}int main(){  std::vector<int > c;  c.push_back(0);  c.push_back(1);  c.push_back(2);  c.push_back(3);  c.push_back(14);  c.push_back(15);// false  好几个是偶数呢 (⊙o⊙)…)  std::cout<<one_of ( c, isOdd ) <<std::endl;//false 好几个 <10  std::cout<<one_of ( c.begin (), c.end (), lessThan10 )  <<std::endl;//true  确实只有一个元素符合条件  std::cout<<one_of ( c.begin () + 3, c.end (), lessThan10 )  <<std::endl;//false 没有一个偶数  std::cout<<one_of ( c.end (), c.end (), isOdd ) <<std::endl;//true 有1个=3  std::cout<<one_of_equal ( c, 3 )  <<std::endl;//false 没有一个符合条件  std::cout<<one_of_equal ( c.begin (), c.begin () + 3, 3 ) <<std::endl;//false 没有一个符合条件  std::cout<<one_of_equal ( c.begin (), c.begin (), 99 )  <<std::endl;  return 0;}

迭代器要求

    假如传递的是迭代器参数,则所有迭代器均使用,除了output迭代器。

时间复杂度

    四个函数的时间复杂度为O(N),他们比较序列中的每一个元素一次,假如超过一个元素满足条件,算法马上返回false,不会继续检查余下元素。

异常安全性
    4个函数通过传值调用或者传常引用调用,不要依赖任何全局变量。因此,4个函数提供了很强的异常安全保证。

0 0
原创粉丝点击