溫馨提示×

c++ count函數(shù)的用法是什么

c++
小億
154
2024-02-26 16:51:31
欄目: 編程語言

count函數(shù)用于統(tǒng)計在指定范圍內(nèi)某個值出現(xiàn)的次數(shù)。其語法如下:

#include <algorithm>

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

其中,InputIt是輸入迭代器的類型,firstlast分別表示要統(tǒng)計的范圍的起始和結束位置,value表示要統(tǒng)計出現(xiàn)次數(shù)的值。函數(shù)返回值為出現(xiàn)次數(shù)。

示例用法:

#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;
}

上述代碼將輸出:

Number of occurrences of 1: 3

0