c++

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

小亿
154
2024-02-26 16:51:31
栏目: 编程语言

count函数用于统计在指定范围内某个值出现的次数。其语法如下:

#include <algorithm>

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

其中,InputIt是输入迭代器的类型,firstlast分别表示要统计的范围的起始和结束位置,value表示要统计出现次数的值。函数返回值为出现次数。

示例用法:

#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
看了该问题的人还看了