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

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

技术教程推荐

深入拆解Tomcat & Jetty -〔李号双〕

Node.js开发实战 -〔杨浩〕

WebAssembly入门课 -〔于航〕

Spark性能调优实战 -〔吴磊〕

数据分析思维课 -〔郭炜〕

深入剖析Java新特性 -〔范学雷〕

大厂广告产品心法 -〔郭谊〕

Web 3.0入局攻略 -〔郭大治〕

云原生基础架构实战课 -〔潘野〕

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