2026-09-10
count_above.cpp
#include <cstddef>
#include <vector>
std::ptrdiff_t count_above(const std::vector<int>& v, int threshold) {
}
vの要素のうちthresholdより大きいものの個数を返すcount_aboveを書いてください。thresholdと等しい要素は数えず、vが空なら0です。count_above({3, 8, 1, 9}, 5) → 2、count_above({5, 5}, 5) → 0、count_above({}, 0) → 0
Reference
#include <algorithm>
std::ptrdiff_t count_above(const std::vector<int>& v, int threshold) {
return std::ranges::count_if(v, [threshold](int x) { return x > threshold; });
}
count_ifに渡す述語は要素を1つ受け取るだけなので、比べる相手のthresholdはラムダの外から持ち込みます。[threshold]と書くと、コンパイラはintのメンバを1つ持つ無名のクラスを作り、ラムダ式を評価した時点のthresholdをそのメンバにコピーします。count_ifが要素ごとに呼ぶのはこのクラスのoperator()で、本体に書いたthresholdはそのメンバを指します。
述語はcount_ifが戻る前に使い終わるので、[&threshold]や[&]で参照を持たせても正しく動きます。int1個ならコピーの手間は参照と変わらないため、ここでは値で持たせました。std::ranges::count_ifの戻り値は範囲の差の型で、std::vector<int>ならstd::ptrdiff_tです。これは参考実装であり、唯一の正解ではありません。