Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

count

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

返回范围内某个元素的数量

返回[first,last]范围内与val相等的元素数量。
该函数使用operator==将单个元素与val进行比较。

这个函数模板的行为相当于:
template <class InputIterator, class T>
  typename iterator_traits<InputIterator>::difference_type
    count (InputIterator first, InputIterator last, const T& val)
{
  typename iterator_traits<InputIterator>::difference_type ret = 0;
  while (first!=last) {
    if (*first == val) ++ret;
    ++first;
  }
  return ret;
}

☲  参数


first, last
指向序列初始和最终位置的输入迭代器。使用的范围是[first,last], 它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。
val
比较的值.
T应该是一种类型,支持与InputIterator使用operator== (将元素作为左侧操作数,val作为右侧操作数)所指向的元素进行比较。

☉  返回值



范围[first,last)中与val相比较结果的元素数。
返回类型(iterator_traits<InputIterator>::difference_type)是signed整型。

☣  示例



// count algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::count
#include <vector>       // std::vector

int main () {
  // counting elements in array:
  int myints[] = {10,20,30,30,20,10,10,20};   // 8 elements
  int mycount = std::count (myints, myints+8, 10);
  std::cout << "10 appears " << mycount << " times.\n";

  // counting elements in container:
  std::vector<int> myvector (myints, myints+8);
  mycount = std::count (myvector.begin(), myvector.end(), 20);
  std::cout << "20 appears " << mycount  << " times.\n";

  return 0;
}

输出:
10 appears 3 times.
20 appears 3 times.

✥ 复杂度



在first 和last之间的distance为线性:对每个元素进行一次比较。。

⇄ 数据竞争


[first,last)范围内的对象被访问(每个对象只被访问一次)。

☂ 异常安全性



如果元素比较或迭代器上的操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。

🍄  另请参阅



for_each 将函数应用于范围(函数模板)
find 在范围内查找值(函数模板)
count_if 返回满足条件的范围内元素个数(函数模板)
replace 替换范围内的值(函数模板)

联系我们 免责声明 关于CandCplus 网站地图