Boost 学习之算法篇 any_of 与 any_of_equal

15 篇文章 0 订阅
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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值