赞
踩
使用时包含的头文件为 #include <numeric>
函数签名:
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init,BinaryOperation binary_op);
函数功能:
对容器指定区间内的元素进行累计操作(默认为值累加),可以自定义操作类型
参数说明:
函数实现:
函数内部实现等价于:
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) {
init = init + *first;
// or: init=binary_op(init,*first) for the binary_op version
++first;
}
return init;
}
应用案例:
#include<iostream> #include<string> #include<vector> #include<algorithm> #include<numeric> using namespace std; // 仿函数:自定义乘法 class MyMultiplication { public: // v1 为累计值 // v2 为元素值 int operator()(const int& v1,const int& v2) { // cout << v1 << " " << v2 << endl; return v1 * v2; } }; // v1 为累计值 // v2 为元素值 int double_add(const int& v1, const int& v2) { return v1 + 2 * v2; } using namespace std; int main() { // 默认累加元素值 vector<int>v = {1,2,3,4,5,6,7,8,9,10}; // 累加器初始值为0 int result= accumulate(v.begin(), v.end(), 0); cout << result << endl; // 55 // 自定义累计操作 累减:使用内置的函数对象 减法 minus int result2 = accumulate(v.begin(), v.end(), 100, minus<int>()); cout << result2 << endl; // 100 -55 = 45 // 自定义累计操作 累乘:传入自定义的函数对象 int result3 = accumulate(v.begin(), v.end(), 1, MyMultiplication()); cout << result3 << endl; // 3628800 // 自定义累计操作 累加2倍的元素值:传入函数指针 int result4 = accumulate(v.begin(), v.end(), 0, double_add); cout << result4 << endl; // 110 return 0; }
使用时包含的头文件为 #include <algorithm>
函数签名:
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val);
函数功能:
将指定值赋值给目标容器指定范围内的所有元素。
需要提前给容器开辟空间。
参数说明:
函数实现:
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
while (first != last) {
*first = val;
++first;
}
}
应用案例:
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; int main() { // 将容器中所有元素赋值为 10(需要提前开辟空间) vector<int> v(10); fill(v.begin(), v.end(), 10); for (vector<int>::iterator p = v.begin(); p != v.end(); p++) { cout << *p << " "; } cout << endl; // 10 10 10 10 10 10 10 10 10 10 return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。