最終更新日時(UTC):
が更新

履歴 編集

function template
<algorithm>

std::any_of(C++11)

namespace std {
  template <class InputIterator, class Predicate>
  bool any_of(InputIterator first,
              InputIterator last,
              Predicate pred);                // (1) C++11

  template <class InputIterator, class Predicate>
  constexpr bool any_of(InputIterator first,
                        InputIterator last,
                        Predicate pred);      // (1) C++20

  template <class ExecutionPolicy, class ForwardIterator, class Predicate>
  bool any_of(ExecutionPolicy&& exec,
              ForwardIterator first,
              ForwardIterator last,
              Predicate pred);                // (2) C++17
}

概要

イテレータ範囲[first, last)のいずれかの要素が条件を満たすかを判定する。

戻り値

イテレータ範囲[first,last) 内のイテレータ i について pred(*i)true になるような要素があればtrueを返し、そうでなければfalseを返す。 イテレータ範囲[first,last)が空の場合はfalseを返す。

計算量

最大で last - firstpred を実行する。

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> v = { 3, 1, 4 };

  std::cout << std::boolalpha;

  // 5 以上の要素が存在するかどうか
  bool result1 = std::any_of(v.begin(), v.end(), [](int x) { return x >= 5; });
  std::cout << result1 << std::endl;

  // 1 の要素が存在するかどうか
  bool result2 = std::any_of(v.begin(), v.end(), [](int x) { return x == 1; });
  std::cout << result2 << std::endl;
}

出力

false
true

実装例

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

バージョン

言語

  • C++11

処理系

関連項目

参照