Boost 学习之算法篇 all_of 与 all_of_equal

15 篇文章 0 订阅

来源:http://www.boost.org/doc/libs/1_54_0/libs/algorithm/doc/html/algorithm/CXX11.html

事实上这篇文章开始的不算是“翻译”,也不算是“原创”。我仅将在官网看到的文档,结合自己的理解放到这里让学习者可以有所收获。


官方API介绍

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

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


/*
头文件“boost/algorithm/cxx11/all_of.hpp” 包括了all_of四个版本的算法。这些算法测试一个序列中的所有元素。如果这些元素的属性相同则返回true。最常用的all_of版本带有一个序列的参数以及一个候选参数。如果候选参数的属性和序列中的所有参数属性一致的话,该函数返回true。
最常用的all_of_equal函数,带有一个值和一个参数序列。如果参数序列中的所有元素和另一个值比较的结果都一致的话返回true。
两个函数都有两种调用格式。第一种格式是带两个迭代器来指定范围,第二种格式带一串使用Boost.Range定义范围的参数序列。
*/

#include <boost/algorithm/cxx11/all_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);

  //这种类型的调用,并没有出现在文章开头的解释中,官方的那一篇文档也没有详细说明。
  //这里说明一下,这是all_of以及all_of_equal的一种形式:将参数序列传递到函数参数中,看返回值是否一致,一致则返回true
  std::cout<<all_of(c,isOdd)<<std::endl;


  std::cout<<all_of(c.begin(),c.end(),lessThan10)<<std::endl;
  std::cout<<all_of(c.begin(),c.begin()+3,lessThan10)<<std::endl;
  std::cout<<all_of(c.end(),c.end(),isOdd)<<std::endl;
  std::cout<<all_of_equal(c,3)<<std::endl;
  std::cout<<all_of_equal(c.begin()+3,c.begin()+4,3)<<std::endl;

  //看这个调用很有意思,为什么会返回true呢?
  //因为两个迭代器包含的范围与第三个参数(所谓的值)比较结果都是一致的!
  std::cout<<all_of_equal(c.begin(),c.begin(),99)<<std::endl;

  return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值