函式模板
<algorithm>

std::all_of

template <class InputIterator, class UnaryPredicate>  bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
測試範圍內所有元素的條件
如果範圍 [first,last) 中的所有元素都滿足 pred 返回 true,或者範圍為空,則返回 true,否則返回 false

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
template<class InputIterator, class UnaryPredicate>
  bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (!pred(*first)) return false;
    ++first;
  }
  return true;
}

引數

first, last
輸入迭代器 指向序列的起始和結束位置。使用的範圍是 [first,last),它包含 first 指向的元素和 last 指向的元素之間的所有元素,但不包含 last 指向的元素。
pred
一元函式,接受範圍內的元素作為引數,並返回一個可轉換為 bool 的值。返回值表示該元素是否滿足此函式檢查的條件。
該函式不得修改其引數。
這可以是函式指標,也可以是函式物件。

返回值

如果 pred 對範圍內的所有元素都返回 true,或者範圍為空,則返回 true,否則返回 false

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
// all_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::all_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {3,5,7,11,13,17,19,23};

  if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
    std::cout << "All the elements are odd numbers.\n";

  return 0;
}

輸出
All the elements are odd numbers.


複雜度

最多線性於 firstlast 之間的 距離:對每個元素呼叫 pred,直到找到不匹配為止。

資料競爭

範圍 [first,last) 中的一些(或全部)物件被訪問(最多一次)。

異常

如果 pred 或迭代器上的操作丟擲異常,則丟擲異常。
請注意,無效的引數會導致 *未定義行為*。

另見