I have a Container of Elements, and each Element has its size()
member function. I have managed to accumulate the total Container Elements size by writing a binary operation add_size
:
#include <algorithm>
#include <vector>
#include <functional>
#include <numeric>
#include <iostream>
class A
{
int size_ ;
public:
A ()
:
size_(0)
{}
A (int size)
:
size_(size)
{}
int size() const
{
return size_;
}
};
template<typename Type>
class add_element
{
Type t_;
public:
add_element(Type const & t)
:
t_(t)
{}
void operator()(Type & t)
{
t += t_;
}
};
int add_size (int i, const A& a)
{
return i+=a.size();
}
using namespace std;
int main(int argc, const char *argv[])
{
typedef vector<A> Vector;
Vector v;
v.push_back(A(10));
v.push_back(A(5));
v.push_back(A(7));
v.push_back(A(21));
v.push_back(A(2));
v.push_back(A(1));
int totalSize = accumulate(v.begin(), v.end(), 0, add_size);
std::cout << totalSize << endl;
return 0;
}
This gives the correct output:
46
And what I would like is to do that without defining the binary operation add_size
just for the size member function, but with using mem_fun and binders. How can I do that? How can I do that effectively? I started out with add_element
and got stuck.
I need the solution to work in C++03.