
On Wed, 26 Jan 2005 17:21:43 -0700, Chris Goller <cgoller@magpiesystems.com> wrote:
I have a struct that contains two values.
struct box { double width; double length; }
vector<box> boxes;
I want to accumlate all the widths of the boxes. The only solution I've found is to create a member function get_width that will return the width for use in mem_fun_ref
eg:
accumulate(make_transform_iterator(boxes.begin(), mem_fun_ref(&boxes::get_width)), make_transform_iterator(boxes.end(), mem_fun_ref(&boxes::get_width)), 0.0, plus<double>()));
Is there a boost way of not using mem_fun_ref, but rather returns the public member variable. Something that could be named mem_var_ref that would look like this:
accumulate(make_transform_iterator(boxes.begin(), mem_var_ref(&boxes::width)), make_transform_iterator(boxes.end(), mem_fun_ref(&boxes::width)), 0.0, plus<double>()));
This way I wouldn't need to add extra get logic to a structure that doesn't really need it othewise.
Thanks,
Chris
Boost.Bind will do what you want, I think - check out this example which sums the x_ members of an array of structs of type A as shown below: #include <boost/bind.hpp> #include <iostream> #include <numeric> #include <functional> #include <algorithm> struct A { int x_; int y_; }; int main(int, char**) { A o[3] = { {1, 2}, {2, 3}, {3, 4} }; int sum = std::accumulate(&o[0], &o[3], 0, boost::bind(std::plus<int>(), boost::bind(&A::x_, _2), _1)); std::cout << sum << "\n"; // Gives the expected answer - 6!! } Rather than use a transform iterator, I've used function composition to transform the argument of type A to an integer (by accessing the x_ member), before applying the std::plus object. HTH Stuart Dootson