It looks like you have a vector of pairs, which is slightly harder to use with std::accumulate() because you need a custom function or function object to handle the summation:
#include <algorithm>
#include <iostream>
#include <utility>
#include <string>
#include <vector>
struct sum_second {
template <typename T, typename U>
U operator()(U sum, std::pair<T, U> next)
{
return sum + next.second;
}
};
int main()
{
std::vector<std::pair<std::string, int> > v;
v.push_back(std::make_pair("a", 1));
v.push_back(std::make_pair("b", 2));
v.push_back(std::make_pair("c", 3));
v.push_back(std::make_pair("d", 4));
int sum = std::accumulate(v.begin(), v.end(), 0, sum_second());
std::cout << "Sum: " << sum << '\n';
} FYI, C++0x simplifies this with an anonymous function by bringing the definition of sum_second and std::accumulate together:
#include <algorithm>
#include <iostream>
#include <utility>
#include <string>
#include <vector>
int main()
{
std::vector<std::pair<std::string, int>> v = {
std::make_pair("a", 1),
std::make_pair("b", 2),
std::make_pair("c", 3),
std::make_pair("d", 4),
};
int sum = std::accumulate(v.begin(), v.end(), 0,
[](int sum, std::pair<std::string, int> next) {
return sum + next.second;
});
std::cout << "Sum: " << sum << '\n';
} Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401