今回はcountについて。その名の通り、コンテナに格納されている特定の要素の数を数えます。
使い方としては、以下の3つくらいでしょうか。
- ベクトルの中に、目的の要素はいくつあるか数える
 - 文字列の中に、目的の文字はいくつあるか数える
 - 配列の中に、目的の要素はいくつあるか数える
 
それぞれ、サンプルソースを載せておきます。
int main () {
    vector<int> nums;
    for (int i = 0; i < 100; i++)
        nums.push_back(rand()%10);
    for (int i = 0; i < 10; i++)
        cout << count(nums.begin(), nums.end(), i) << endl;
    return 0;
}
int main () {
    string name = "tanaka tarou";
    cout << count(name.begin(), name.end(), 'a') << endl;
    return 0;
}
int main () {
    double x[] = {0.0, 0.1, 0.14, 0.0, 0.3, 0.6};
    int sz = sizeof(x) / sizeof(double);
    cout << count(x, x+sz, 0.0) << endl;
    return 0;
}
0 件のコメント:
コメントを投稿