std::count if

提供: C++入門
移動: 案内検索
スポンサーリンク

std::count_if とは、第3引数で与えられる単項関数(Unary function)の条件を満たす要素が配列やコンテナにいくつ含まれているか返すテンプレート関数です。

読み方

std::count_if
えすてぃーでぃー かうんと いふ

概要

std::countboost::countでは、コンテナに含まれる特定の要素を数えることができますが、奇数(odd)を数える、といったことはできませんでした。 std::count_ifでは、単項関数を与えることにより、柔軟な条件を指定して、数えることができます。。

count_if1.cpp の例

ソースコード count_if1.cpp

これは、std::vectorの奇数(odd)の数を数える例です。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool is_odd (int i) {
        return ( (i%2) == 1);
}
int main(int argc, char const* argv[])
{
        vector<int>     v;
        for (int i = 0; i < 10; i++) {
                v.push_back(i);
        }
        size_t n_count = std::count_if(v.begin(), v.end(), is_odd);
        std::cout << n_count << std::endl;
        return 0;
}

コンパイル

g++  count_if1.cpp -o count_if1

実行例

% ./count_if1
5

count_if2.cpp の例

ソースコード count_if2.cpp

このサンプルは、ラムダ式を用いたバージョンです。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool is_odd (int i) {
        return ( (i%2) == 1);
}
int main(int argc, char const* argv[])
{
        vector<int>     v;
        for (int i = 0; i < 10; i++) {
                v.push_back(i);
        }
        size_t n_count = std::count_if(v.begin(), v.end(),
                        [](int i)->bool{return ( (i%2) == 1);}
                        );
        std::cout << n_count << std::endl;
        return 0;
}

コンパイル

clang++ -std=c++11  count_if2.cpp -o count_if2

実行例

% ./count_if2
5

関連項目




スポンサーリンク