1,accumate函数
template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init,
BinaryOperation op );
效果:计算[first, last]范围内元素与init的总和。
版本1使用操作符“+”实现求和运算
版本2使用函数op实现求和运算,op的原型必须满足:Ret fun(const Type1 &a, const Type2 &b);
所以事实上用版本二可以实现任意的算术运算或其他操作,而不仅限于求和;
/*******************************************************************/
// 验证accumulate
/*******************************************************************/
int i_arr[] = {1, 2,3};
vector<int> ivec(i_arr, i_arr+3);
int sum_1 = accumulate(ivec.begin(), ivec.end(),1);
int sum_2 = accumulate(ivec.begin(), ivec.end(),1,int_multiply);
cout << "sum_1: " << sum_1 << endl;
cout << "sum_2: " << sum_2 << endl;
其中int_multiple()是已定义的函数,其实现如下:
int int_multiply(int &i1, int &i2)
{
//return i1*i1 + i2*i2
return i1*i2;
}
则输出为:
sum_1: 7 (1+1+2+3)
sum_2: 6 (1*1*2*3)
注意:函数里的init是必不可少的,不然函数无法得知数据类型。
2,count函数
template< class InputIt, class T >
typename iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T &value );
template< class InputIt, class UnaryPredicate >
typename iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPredicate p );
Returns the number of elements in the range
[first, last)
satisfying specific criteria. The first version counts the elements that are equal to
value
, the second version counts elements for which predicate
p
returns
true
.
效果:统计[first, last)间满足条件的元素个数。
版本1统计值为value的元素个数;
版本2统计使谓词p返回true的元素个数,bool pred(const Type &a);