Boost 学习之算法篇 any_of 与 any_of_equal

来源:互联网 发布:android手机助手源码 编辑:程序博客网 时间:2024/06/05 09:46
any_of 与any_of_equal
这个算法测试一个序列的元素,假如有任何一个元素拥有特定的属性,则返回true。此处的特定指的是(和算法所带的参数比较能够返回true)

常用的any_of 带一个参数序列和一个候选值。如果候选值对于序列中的任何元素比较至少有一个返回true则该算法返回true。

常用的any_of_equal带一个参数序列和一个值.如果序列中的任何元素与传递的值比较的结果至少有一个相等则返回true。

两个常用的算法有两种调用形式.第一种带一对迭代器,用来标记参数的范围.第二种形式带一个用Boost.Range转换的单一范围参数。

来源:http://www.boost.org/doc/libs/1_60_0/libs/algorithm/doc/html/the_boost_algorithm_library/CXX11/any_of.html


函数API官方说明

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


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

举例说明

/*这个算法测试一个序列的元素,假如有任何一个元素拥有特别的属性,则返回true常用的any_of 带一个参数序列和一个候选值。如果候选值对于序列中的任何元素比较至少有一个返回true则该算法返回true。常用的any_of_equal带一个参数序列和一个值.如果序列中的任何元素与传递的值比较的结果至少有一个相等则返回true。两个常用的算法有两种调用形式.第一种带一对迭代器,用来标记参数的范围.第二种形式带一个用Boost.Range转换的单一范围参数.*/#include <boost/algorithm/cxx11/any_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);  //true  std::cout<<any_of(c,isOdd)<<std::endl;  //true  std::cout<<any_of(c.begin(),c.end(),lessThan10)<<std::endl;  //false  std::cout<<any_of(c.begin()+4,c.end(),lessThan10)<<std::endl;  //false  why?  //因为传递过去的范围是空,里面的元素与value(元素传递到地址所指向的函数)比较返回的都是false,因此这一句话返回false  std::cout<<any_of(c.end(),c.end(),isOdd)<<std::endl;  //true  std::cout<<any_of_equal(c,3)<<std::endl;  //false  //因为传递过去的范围,里面的元素与predicate比较返回的都是false,因此这一句话返回false  std::cout<<any_of_equal(c.begin(),c.begin()+3,3)<<std::endl;  //false  std::cout<<any_of_equal(c.begin(),c.begin(),99)<<std::endl;  return 0;}




0 0