count_ifとは?
- 配列において指定した条件を満たす要素の個数を取得できる関数です。
- 参考サイト:count_if - cpprefjp C++日本語リファレンス
- 引数、返り値を以下に示す。
第一引数 | 配列の先頭イテレータ |
---|---|
第二引数 | 配列の末尾イテレータ |
第三引数 | 条件式(ラムダ式) |
返り値 | 条件式を満たす要素数 |
使用例
(1) 偶数の要素数を取得
ソースコード
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v = { 2, 3, 4, 6, 7}; // 「a」を含む文字が何個あるか調査 auto count = std::count_if( v.begin(), v.end(), [](int a) { return (a % 2 == 0); } ); std::cout << "偶数の要素数: " << count << std::endl; }
実行結果
偶数の要素数: 3
(2) 「a」を含む文字列の数を取得
ソースコード
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<std::string> v = { "and", "on", "at", "between", "of" }; // 「a」を含む文字が何個あるか調査 auto count = std::count_if( v.begin(), v.end(), [](std::string s) { return (s.find('a')!=std::string::npos); } ); std::cout << "「a」を含む文字の数: " << count << std::endl; }
実行結果
「a」を含む文字の数: 2