Boost.Accumulators: how to use with object data members?
Hi, Is it possible to use Boost.Accumulators on data members of a class, with a UnaryFunction or Lamba function ? E.g. struct Data { double data; }; vector<Data> v; // Insert some Data objects here.... accumulator_set< double, features< tag::variance > > acc; acc = for_each( v.begin(), v.end(), ??????? ); cout << "Variance: " << variance(acc) << std::endl; where ???? is an arbitrary UnaryFunction or Lamda function something like "bind<void>( ref(acc), bind(&Data::data, _1)) )" (which did not do the trick) TIA -- Groeten, Joost Kraaijeveld Askesis B.V. Molukkenstraat 14 6524NB Nijmegen tel: 024-3888063 / 06-51855277 fax: 024-3608416 web: www.askesis.nl
accumulator_set< double, features< tag::variance > > acc; acc = for_each( v.begin(), v.end(), ??????? );
using namespace std; using namespace boost; struct data{ data(double value):value_(value){} double value_; }; int main() { typedef std::vector<data> vec_t; vec_t vec; vec.push_back(data(2.0)); vec.push_back(data(1.0)); typedef accumulators::accumulator_set< double, accumulators::features< accumulators::tag::moment<2> > > acc_t; acc_t acc; for_each( begin(vec), end(vec), bind<void>( ref(acc), bind<double>( &data::value_, _1 ) ) ); double result = accumulators::moment<2>(acc); // = 4 + 1 /2 = 2.5 NB: acc = has been ommitted.
On Sun, 2009-04-12 at 13:15 -0400, er wrote:
[snip] NB: acc = has been ommitted.
Cool, it works as advertised ;-) Could you try to enlighten and attempt to explain why your solution works? Especially, why does it work without the assignment which is the example from the docs? BTW: I have not tried it (yet) but should it work with Lambda functions (e.g. calling member function instead of data members)? Thanks again, -- Groeten, Joost Kraaijeveld Askesis B.V. Molukkenstraat 14 6524NB Nijmegen tel: 024-3888063 / 06-51855277 fax: 024-3608416 web: www.askesis.nl
Especially, why does it work without the assignment which is
the example from the docs?
The example from the docs is acc = std::for_each( data.begin(), data.end(), acc ); In your case the function object is not acc but bind<void>(...ref(acc)...).
Hi, Sorry about the last post: it works OK with a member function and bind: std::for_each(data.begin(), data.end(), boost::bind<void>( boost::ref(acc), boost::bind<long>(&Data::getData,_1)) ); -- Groeten, Joost Kraaijeveld Askesis B.V. Molukkenstraat 14 6524NB Nijmegen tel: 024-3888063 / 06-51855277 fax: 024-3608416 web: www.askesis.nl
participants (2)
-
er
-
Joost Kraaijeveld