返回值一定是int
#include <iostream>
#include <functional>
#include <string>
#include<vector>
#include<deque>
#include<algorithm>
#include<numeric>
#include<map>
using namespace std;
struct Account
{
int money;
};
int main()
{
vector<int> vi{ 10, 20, 30 };
vector<Account> accs{ {100},{200},{300} };
map<string, int> m{ {"dog",3,},{"cat",2} ,{"fox",1 } ,{"crow",2}};
cout << accumulate(vi.begin(), vi.end(), 0, plus<int>()) << endl;
cout << accumulate(vi.begin(), vi.end(), 0, [](int i, int j)->int {return i + j; }) << endl;
cout << accumulate(accs.begin(), accs.end(), 0, bind(plus<int>(), placeholders::_1, bind(&Account::money, placeholders::_2))) << endl;
cout << accumulate(m.begin(),m.end(),0,bind(plus<int>(), placeholders::_1,bind(&map<string,int>::value_type::second, placeholders::_2))) << endl;
}
#include <iostream>
#include <functional>
#include <string>
#include<vector>
#include<deque>
#include<algorithm>
#include<numeric>
#include<map>
using namespace std;
using InputIterator = vector<int>::iterator;
using T = int;
using BinaryOpertion = function<int(int, int)>;
int accumulate(InputIterator first, InputIterator last, T init)
{
for (;first != last ; ++first) init = init + *first;
return init;
}
int accumulate(InputIterator first, InputIterator last, T init, BinaryOpertion binary_op)
{
for (;first != last ;++first) init = binary_op(init,*first);
return init;
}
int main()
{
vector<int> vi{ 10, 20, 30 };
cout << accumulate(vi.begin(),vi.end(),0) << endl;
cout << accumulate(vi.begin(), vi.end(), 0, [](int i, int j)->int {return i + j;}) << endl;
}
标签:求和,累加,int,init,InputIterator,accumulate,using,include,first
From: https://blog.csdn.net/WNX10086/article/details/140575120