新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c++ count函数的有哪些作用,c++ count()

发布时间:2023-11-03 12:01:13

c++ count函数的有哪些作用

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。