How to accumulate a two dimensional array with std::for_each?
Code:std::vector<std::vector<long> > v;
std::for_each(v.begin(), v.end(), ????);
Printable View
How to accumulate a two dimensional array with std::for_each?
Code:std::vector<std::vector<long> > v;
std::for_each(v.begin(), v.end(), ????);
When you say accumulate, are you thinking of std::accumulate instead of std::for_each()?
Anyway, it is quite simple: just make the function or function object able to handle a std::vector<long> as the argument.
You mean something like this?
I dont see the advantage anymore of just doing it the "old fashioned" way then with a loop. Was hoping for a better solutionCode:class Acc
{
public:
Acc() : m_total(0) {}
void operator()(std::vector<long> &v)
{
m_total += std::accumulate(v.begin(), v.end(), 0);
}
private:
long m_total;
};
No.
You need to use `std::accumulate' correctly and ignore `std::for_each'.
In other words, use a tool that was designed to solve the problem you want to solve.
Edit: Not that you can't do it with `std::for_each'; you just need to use one or the other.
Soma
Im just asking if there is a one-liner to accumulate all items in a vector of vector of long. Doesnt matter if I use accumulate or for_each or whatever
??Code:vector<vector<long> > v;
total = sum(v.begin(), v.end(), 0);
If you are so keen on doing it as a one-liner, you might read on nesting STL algorithms with Boost.Lambda. :)
Perhaps it just ain't worth it...
-----
With a struct it might look like this (a bit simpler than yours, and the struct could technically be a free function):
Code:#include <vector>
#include <numeric>
#include <iostream>
using namespace std;
struct subaccumulator {
long operator()(long r, const vector<long>& v) const
{
return r + accumulate(v.begin(), v.end(), 0l);
}
};
int main()
{
vector<vector<long> > v(2, vector<long>(3, 4)); //2 by 3 all 4's
cout << accumulate( v.begin(), v.end(), 0l, subaccumulator()) << '\n';
}
"Im just asking if there is a one-liner to accumulate all items in a vector of vector of long."
Yes. Infinitely many...
Of course, that doesn't mean that you will not have to code some support routines yourself, but then that's the beauty of C++ generics. You will only have to code it once!
Soma