頭文件 'boost/algorithm/cxx11/one_of.hpp' 包含4個名爲one_of的常用算法.
該算法測試序列中的所有參數,假如測試這些元素髮現其中只有一個含有特別的屬性,則返回true.
常用的one_of 函數帶有一個參數序列以及一個候選值。假如用候選值與參數序列中所有元素只有一個返回true,則該函數將返回true。
常用的one_of_equal 函數帶一個參數序列和一個值。假如參數序列中只有一個值和傳入的值比較相同,則返回true。
上述兩個函數都有兩種調用方式:第一種方式帶了一對迭代器,用來標記參數範圍;第二種方式方式帶了一個用Boost.Range轉換後的範圍參數。
請特別注意上述關鍵字:只有一個!
官方API
namespace boost { namespace algorithm {
template<typename InputIterator, typename Predicate>
bool one_of ( InputIterator first, InputIterator last, Predicate p );
template<typename Range, typename Predicate>
bool one_of ( const Range &r, Predicate p );
}}
namespace boost { namespace algorithm {
template<typename InputIterator, typename V>
bool one_of_equal ( InputIterator first, InputIterator last, V const &val );
template<typename Range, typename V>
bool one_of_equal ( const Range &r, V const &val );
}}
舉例詳解]
#include <boost/algorithm/cxx11/one_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);
// false 好幾個是偶數呢 (⊙o⊙)…)
std::cout<<one_of ( c, isOdd ) <<std::endl;
//false 好幾個 <10
std::cout<<one_of ( c.begin (), c.end (), lessThan10 ) <<std::endl;
//true 確實只有一個元素符合條件
std::cout<<one_of ( c.begin () + 3, c.end (), lessThan10 ) <<std::endl;
//false 沒有一個偶數
std::cout<<one_of ( c.end (), c.end (), isOdd ) <<std::endl;
//true 有1個=3
std::cout<<one_of_equal ( c, 3 ) <<std::endl;
//false 沒有一個符合條件
std::cout<<one_of_equal ( c.begin (), c.begin () + 3, 3 ) <<std::endl;
//false 沒有一個符合條件
std::cout<<one_of_equal ( c.begin (), c.begin (), 99 ) <<std::endl;
return 0;
}
迭代器要求
假如傳遞的是迭代器參數,則所有迭代器均使用,除了output迭代器。
時間複雜度
四個函數的時間複雜度爲O(N),他們比較序列中的每一個元素一次,假如超過一個元素滿足條件,算法馬上返回false,不會繼續檢查餘下元素。
異常安全性
4個函數通過傳值調用或者傳常引用調用,不要依賴任何全局變量。因此,4個函數提供了很強的異常安全保證。