溫馨提示×

c++ count函數的作用是什么

c++
小億
158
2023-11-03 12:01:13
欄目: 編程語言

C++的count函數是用來計算指定元素在容器中出現的次數的。

count函數的用法如下:

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

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

    // 計算容器中元素1的個數
    int count = std::count(numbers.begin(), numbers.end(), 1);
    std::cout << "Number of 1s: " << count << std::endl;

    return 0;
}

輸出結果為:

Number of 1s: 4

上述代碼中,count函數接受三個參數:容器的起始迭代器、容器的結束迭代器和要計算的目標元素。它會遍歷容器中的每個元素,然后返回目標元素在容器中出現的次數。

在上述示例中,容器numbers中元素1出現了4次,所以輸出結果為4。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女