温馨提示×

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

c++
小亿
97
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