How to combine back_inserter with a transformation, C++

  • A+
Category:Languages

How can I wrap an OutputIterator such as back_inserter_iterator with a transformation? Consider

std::vector<double> xx; std::vector<double> yy; std::vector<double> diff; auto ba = std::back_inserter(diff); std::set_difference(xx.begin(), xx.end(), yy.begin(), yy.end(), ba); 

I would like to apply a free function f(double) or g(std::vector<double>::iterator) before pushing back to the diff vector:

Specifically, how can I store the addresses of the diff elements (or iterators) instead of the elements themeselves.

std::vector<double&> diff; auto baAdr = ??? std::back_inserter( ??? (diff));  std::set_difference(xx.begin(), xx.end(), yy.begin(), yy.end(), baAdr); 

For performance reasons (the real data is big) I do not want to construct a temporary vector and std::transform from it. It would also not work for non-copyable, movable types.

I can use boost.


With boost::function_output_iterator:

#include <vector> #include <algorithm> #include <boost/function_output_iterator.hpp>  int main()  {     std::vector<double> xx;     std::vector<double> yy;     std::vector<const double*> diff;  // const pointers, or else you                                       // need a const_cast in lambda      std::set_difference(xx.begin(), xx.end(), yy.begin(), yy.end(),         boost::make_function_output_iterator(             [&diff](const double& d) { diff.push_back(&d); }         )     ); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: