Boost 學習之算法篇 any_of 與 any_of_equal

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;
}




發佈了57 篇原創文章 · 獲贊 21 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章