C++ 算法 中的 count函数

首页 / C++入门教程 / C++ 算法 中的 count函数

C++算法count()函数接受'val'作为参数,并比较参数内元素'val'的出现。返回该元素的出现次数。

count - 语法

template <class InputIterator, class T>

typename iterator_traits<InputIterator>::difference_type count (InputIterator first, InputIterator last, const T& val);

count - 参数

first:它是参数中第一个元素的输入迭代器。

last:它是参数中最后一个元素的输入迭代器。

val :这是在参数中搜索其出现的元素。

count - 返回值

该函数返回参数为[first,last)的元素" val"的出现次数。

count - 例子1

#include<iostream>
#include<algorithm>
#include<vector>
using namespace  std;
int main()
{
	int newints[]={50,60,70,70,60,50,50,60};
	int newcount=std::count(newints, newints+8, 50);
	std::cout<<"50 appear "<<newcount<<"times.\n";
	std::vector<int> newvector(newints, newints+8);
	newcount=std::count(newvector.begin(),newvector.end(),70);
	std::cout<<"70 appear "<<newcount<<"times.\n";
	return 0;
}

输出:

50 appear 3 times.
70 appear 2 times.

count - 例子2

#include <bits/stdc++.h>
using namespace std;
int main()
{
	int ar[]={6,4,2,6,6,10,6};
	int n = sizeof(ar)/sizeof(ar[0]);
	cout<<"The number of times 6 appear is:"<<count(ar,ar+n,6);
	return 0;
}

输出:

The number of times 6 appear is: 4

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

浏览器工作原理与实践 -〔李兵〕

后端存储实战课 -〔李玥〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

物联网开发实战 -〔郭朝斌〕

Spring编程常见错误50例 -〔傅健〕

程序员的个人财富课 -〔王喆〕

云原生架构与GitOps实战 -〔王炜〕

B端体验设计入门课 -〔林远宏(汤圆)〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)