Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-12-10) 阅读数 11 #程序编程
文章标签 c++

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。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门