STL any_of算法

本文內容來自C++Plus,本文只是本人的總結和翻譯而已。本人只是C++的搬運工。

原文傳送門:http://www.cplusplus.com/reference/algorithm/any_of/

any_of算法:測試區間範圍內個別元素符合測試條件。

template<class InputIterator, class UnaryPredicate>
  bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return true;
    ++first;
  }
  return false;
}

如果[first,last)區間中被指定的測試元素符合測試條件,就返回true,如果[first,last)是空的,就返回false。

// any_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::any_of
#include <array>        // std::array

int main () {
  std::array<int,7> foo = {0,1,-1,3,-3,5,-5};

  if ( std::any_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
    std::cout << "There are negative elements in the range.\n";

  return 0;
}


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