C++学习笔记27——泛型算法之统计(accumate count)
2015-11-21 18:35
696 查看
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
preturns true.
效果:统计[first, last)间满足条件的元素个数。
版本1统计值为value的元素个数;
版本2统计使谓词p返回true的元素个数,bool pred(const Type &a);
相关文章推荐
- C++赋值操作符重载简介
- C++赋值操作符重载简介
- C++11 为自定义容器实现标准的forward迭代器
- C语言扫雷
- c语言俄罗斯方块
- c++排序算法
- c语言贪吃蛇
- c语言:输入一个数,从高位向低位输出,如:输入12345,输出1 2 3 4 5
- C语言王国探秘一
- 【C语言】 实现strncpy,strncat,strncmp
- C语言模拟实现memset.memcmp函数
- c语言:给十个整数比较大小
- c语言:4种方法;交换两个整数的位置(包括引入第三方变量和不引入第三方变量)
- c语言:2种方法;求两个整数之中的较大者
- C语言实验——单词统计
- 浅谈C语言中如何取随机数
- C语言:求两个整数之和
- 模拟实现C语言strncpy.strncat.strncmp函数
- C语言:在屏幕上输出信息
- C++学习笔记26——泛型算法之容器元素排序(sort unique)