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

履歴 編集

function template
<algorithm>

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

namespace std::ranges {
  template <input_iterator I,
            sentinel_for<I> S,
            class Proj = identity,
            indirect_unary_predicate<projected<I, Proj>> Pred>
  constexpr iter_difference_t<I>
    count_if(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 range_difference_t<R>
    count_if(R&& r, Pred pred, Proj proj = {});           // (2) C++20
}

概要

条件を満たしている要素の数を数える。

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

戻り値

[first,last) 内のイテレータ i について、invoke(pred,invoke(proj, *i)) != false であるイテレータの数を返す

計算量

正確に last - first 回の述語の適用を行う

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

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

  // 値が 1 または 3 の要素がいくつあるかを数える
  auto count = std::ranges::count_if(v, [](int x) { return x == 1 || x == 3; });
  std::cout << "count of 1 or 3: " << count << std::endl;
}

出力

count of 1 or 3: 5

実装例

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

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

inline constexpr count_if_impl count_if;

バージョン

言語

  • C++20

処理系

参照