std::vector 特定の要素をカウントする

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

std::countstd::count_ifは、コンテナのある要素をカウントできます。std::countを使用して、std::vector の特定の要素がカウントできます。

読み方

std::vector
えすてぃーでぃー べくたー
std::count
えすてぃーでぃー かうんと

概要

std::countは、特定の値を指定して、カウントします。 std::count_ifは、評価関数を与えて、マッチしたものをカウントします。

カウントのテンプレートの詳細については、std::countstd::count_ifをご参照ください。

count2.cpp の例

ソースコード count2.cpp

この例では、std::vectorの中の4の数を数えます。

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char const* argv[])
{
        int i_array [] = {1, 2, 2, 3, 4, 4, 4, 5};
        vector<int>     v(i_array, i_array+sizeof(i_array));
        size_t n_count = std::count(v.begin(), v.end(), 4);
        std::cout << n_count << std::endl;
        return 0;
}

コンパイル

g++  count2.cpp -o count2

実行例

% ./count2
3

std::count_ifの例 count_if1.cpp

奇数(odd number)をカウントする例です。 奇数というのは、2で割り切れない数で、1,3,5,7,9 のような数です。

ソースコード count_if1.cpp

これは、std::vectorの奇数(odd)の数を数える例です。 評価関数 is_odd を std::count_ifに与えて、実行します。

#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

実行例

奇数は、5個見つかりました。

% ./count_if1
5

std::count_ifの例 count_if2.cpp

奇数(odd number)をカウントする例です。 奇数というのは、2で割り切れない数で、1,3,5,7,9 のような数です。

ソースコード 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

実行例

奇数は、5個見つかりました。

% ./count_if2
5

関連項目




スポンサーリンク