Boost 學習之算法篇 is_partitioned

is_partitioned

頭文件 'is_partitioned.hpp' 包含is_partitioned 算法的的兩個變種. 該算法測試一個序列T是否按照某個謂詞來劃分的;換句話說滿足該爲此的元素都在序列的開頭。

常用的is_partitioned 函數帶有一個參數序列和一個謂詞參數.假如序列按照謂詞劃分則返回true。

is_partitioned 有兩種調用格式:第一種是帶一對迭代器,用來表示參數範圍。第二種形式帶一個範圍的參數,這些參數被Boost.Range便利過。

官方API

template<typename InputIterator, typename Predicate>
	bool is_partitioned ( InputIterator first, InputIterator last, Predicate p );
template<typename Range, typename Predicate>
	bool is_partitioned ( const Range &r, Predicate p );

舉例詳解

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

  //false 並不是按照謂詞(偶數)劃分的。要返回true應該是偶數在前,奇數在後
  std::cout<<is_partitioned ( c, isOdd ) <<std::endl;

  //true 小於10的在前,大於的在後,因此返回true
  std::cout<<is_partitioned ( c, lessThan10 )  <<std::endl;

  //true
  std::cout<<is_partitioned ( c.begin (), c.end (), lessThan10 )  <<std::endl;

  //true
  std::cout<<is_partitioned ( c.begin (), c.begin () + 3, lessThan10 ) <<std::endl;

  //true 特例,爲空的序列一律返回true
  std::cout<<is_partitioned ( c.end (), c.end (), isOdd )  <<std::endl;
  return 0;
}

迭代器要求

       不能作用於output迭代器!其他迭代器都行。

時間複雜度
    O(N)。兩個函數會比較序列中的每一個元素,當發現任一個元素不符合謂詞劃分要求時候,立即返回,餘下的元素不會被測試到。

異常安全
    兩個函數都是通過傳值或者通過常引用傳參數。不要依賴任何全局變量的行爲。因此,兩個函數都提供了強異常安全保證。

注意

    The iterator-based version of the routine is_partitioned is part of the C++11 standard. When compiled using a C++11 implementation, the implementation from the standard library will be used.
    對於空的參數序列,一律返回true。



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