Inversion of boost :: make_function_output_iterator

The boost function make_function_output_iterator converts a function that would be suitable for std :: for_each in an iterator suitable for std :: copy. There is a boost function that does the opposite. That is, it takes an iterator corresponding to std :: copy and converts it into a function suitable for std :: for_each.

So, if I have an output iterator output_iter. I need

for_each(v1.begin(), v1.end(), make_output_iterator_function(output_iter));

To do the same thing as

copy(v1.begin(), v1.end(), output_iter);
+3
source share
3 answers

Perhaps std::insert_iteratoror std::transformwhat are you looking for?

You can bind std::insert_iterator::operator=, which makes an insert on every call, with some witchcraft boost::bind:

#include <boost/bind.hpp>
#include <vector>
#include <iterator>
#include <algorithm>

    typedef std::vector<int> Container;
    typedef std::insert_iterator< Container > InsertIt;

int main(){
    Container v1, v2;
    InsertIt insert_it (v2,v2.end());
    std::for_each(v1.begin(), v1.end(),
            boost::bind(static_cast<InsertIt& (InsertIt::*)(typename Container::const_reference)>(&InsertIt::operator=), insert_it, _1));
}
+1

 template<typename T>
 struct iterator_to_function {
      T iter_;
      iterator_to_function(const T& iter) : iter_(iter) {}
      template<typename T2>
      T& operator()(const T2& elem) {*iter_=elem; return ++iter_;}
 };

template<class T>
iterator_to_function<T> make_iterator_function(const T& iter) 
{
  return iterator_to_function<T>(iter);
}

.

typedef vector<int> t_vec;
t_vec v;
t_vec v2;
for_each(v.begin(), v.end(), 
         make_iterator_function(back_inserter(v2));
+1

If you have an option, I would do it with lambdas, and not std/boost::bind, for example:

std::vector<type> v1;
std::for_each(v1.begin(), v1.end() [&output_iter](const type& t) {*output_iter++ = t});

Of course, it would be wiser to just use it std::copyfirst!

+1
source

All Articles