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

履歴 編集

function template
<algorithm>

std::ranges::any_of(C++20)

namespace std::ranges {
  template <input_iterator I,
            sentinel_for<I> S,
            class Proj = identity,
            indirect_unary_predicate<projected<I, Proj>> Pred>
  constexpr bool
    any_of(I first, S last, Pred pred, Proj proj = {}); // (1) C++20

  template <input_range R,
            class Proj = identity,
            indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
  constexpr bool
    any_of(R&& r, Pred pred, Proj proj = {});           // (2) C++20
}

概要

範囲のいずれかの要素が条件を満たすかを判定する。

テンプレートパラメータ制約

戻り値

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

計算量

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

#include <algorithm>
#include <iostream>
#include <array>

int main() {
  constexpr std::array v = { 3, 1, 4 };

  std::cout << std::boolalpha;

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

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

出力

false
true

実装例

struct any_of_impl {
  template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred>
  constexpr bool operator()(I first, S last, Pred pred, Proj proj = {}) const {
    for ( ; first != last; ++first)
      if (invoke(pred, invoke(proj, *first))) return true;
    return false;
  }

  template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
  constexpr bool operator()(R&& r, Pred pred, Proj proj = {}) const {
    return (*this)(begin(r), end(r), ref(pred), ref(proj));
  }
};

inline constexpr any_of_impl any_of;

バージョン

言語

  • C++20

処理系

関連項目

参照