Boost 學習之算法篇 all_of 與 all_of_equal

來源: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;
}


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