STL Algorithm 之count

count

template<class InputIterator, class Type>
   typename iterator_traits<InputIterator>::difference_type count(
      InputIterator _First, 
      InputIterator _Last, 
      const Type& _Val
   );

Parameters

_First

An input iterator addressing the position of the first element in the range to be traversed.

_Last

An input iterator addressing the position one past the final element in the range to be traversed.

_Val

The value of the elements to be counted.

Return Value

The difference type of the InputIterator that counts the number of elements in the range [ _First, _Last ) that have value _Val.

Remarks

The operator== used to determine the match between an element and the specified value must impose an equivalence relation between its operands.

count_if

template<class InputIterator, class Predicate>
   typename iterator_traits<InputIterator>::difference_type count_if(
      InputIterator _First, 
      InputIterator _Last,
      Predicate _Pred
   );

Parameters

_First

An input iterator addressing the position of the first element in the range to be searched.

_Last

An input iterator addressing the position one past the final element in the range to be searched.

_Pred

User-defined predicate function object that defines the condition to be satisfied if an element is to be counted. A predicate takes single argument and returns true or false.

Return Value

The number of elements that satisfy the condition specified by the predicate.

Remarks

This template function is a generalization of the algorithm count, replacing the predicate "equals a specific value" with any predicate.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool cmp(int& a)
{
	return a < 5;
}

int main()
{
	
	vector<int>test;
	test.push_back(1);
	test.push_back(1);
	test.push_back(1);
	test.push_back(8);
	test.push_back(2);

	vector<int>::iterator::distance_type res;

	res = count(test.begin(), test.end(), 1);
	cout << res << endl;

	res = count_if(test.begin(), test.end(), cmp);
	cout << res << endl;
	getchar();
	
	return 0;
}

 

转载于:https://my.oschina.net/pirtt/blog/879206

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值