count 源码剖析

一:用法解析
函数原型:

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

不理解typename的含义可以参考http://blog.csdn.net/laojiu_/article/details/51737114

功能:

在区间[ first , last )找到与val相等的数,返回其个数。

例子:

// 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.


二:源码剖析
// TEMPLATE FUNCTION count
template<class _InIt,
	class _Ty> inline
	typename iterator_traits<_InIt>::difference_type
		_Count_np(_InIt _First, _InIt _Last, const _Ty& _Val)
	{	// count elements that match _Val
	typename iterator_traits<_InIt>::difference_type _Count = 0;

	for (; _First != _Last; ++_First)
		if (*_First == _Val)
			++_Count;
	return (_Count);
	}

template<class _InIt,
	class _Ty> inline
	typename iterator_traits<_InIt>::difference_type
		count(_InIt _First, _InIt _Last, const _Ty& _Val)
	{	// count elements that match _Val
	_DEBUG_RANGE(_First, _Last);
	return (_Count_np(_Unchecked(_First), _Unchecked(_Last), _Val));
	}




源码摘抄自Visual Studio 2015安装目录algorithm文件中。



点击进入目录----> C++源码剖析目录





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值