C++ count関数:文字列/配列の要素数を数える方法

count関数は、指定された範囲内で特定の値が出現する回数を数えるために使用されます。その構文は以下のようになります:

#include <algorithm>

int count(InputIt first, InputIt last, const T &value);

InputItは入力イテレータの種類であり、firstとlastはそれぞれ統計される範囲の開始と終了位置を示し、valueは出現回数を統計する値を表す。関数の戻り値は出現回数である。

使用例:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 1, 2, 1, 4};

    int num = std::count(vec.begin(), vec.end(), 1);

    std::cout << "Number of occurrences of 1: " << num << std::endl;

    return 0;
}

The above code will output:
上記のコードは出力されます:

Number of occurrences of 1: 3
bannerAds