C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ count()

C++ 算法函数count()

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

语法

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

参数

first: 它是范围中第一个元素的输入迭代器。
last: 它是范围中last元素的输入迭代器。
val : 它是要在范围中搜索其出现的元素。

返回值

该函数返回元素" val"在[first,last)范围内的出现次数。

示例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.

示例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

复杂度

该函数的复杂度与第一个元素和last元素之间的距离呈线性关系。

数据竞争

访问范围的某些或全部元素

异常

如果任何参数抛出一个异常,该函数将引发异常。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4