tags:

views:

35

answers:

1

Normally someone would just go and grab Boost's Function Output Iterator but I'm not allowed to use Boost at work. That said, I just want to use the copy function to traverse a collection, call a function on each item, take the output of that function, and finally push_back it onto another collection. I've written some code:

#include <iterator>
using std::iterator;
using std::output_iterator_tag;

template<typename Container, typename Function>
struct Back_Transform_Iterator : public iterator<output_iterator_tag,void,void,void,void>{
    explicit Back_Transform_Iterator(Container &_container, const Function &_function) 
        : m_Container(_container),
        m_Function(_function){}

    Back_Transform_Iterator<Container,Function>& operator= (const typename Function::argument_type &value){ 
      m_Container.push_back( m_Function( value ) );

      return *this; 
    }

    Back_Transform_Iterator<Container,Function>& operator* (){ return *this; }
    Back_Transform_Iterator<Container,Function>& operator++ (){ return *this; }
    Back_Transform_Iterator<Container,Function> operator++ (int){ return *this; }

    typedef Container container_type;

private:
    Container   &m_Container;
    Function    m_Function;
};

template<typename C, typename F>
Back_Transform_Iterator<C,F> back_transform_inserter(C &_container, F &_unary_function){
    return Back_Transform_Iterator<C,F>( _container, _unary_function );
}

but... I'm getting compilation problems. Fairly certain it's to do with the operator*() call. I have no idea how to effectively dereference the container's objects so that they object the function's effects. Error:

error C2582: 'operator =' function is unavailable in 'Back_Transform_Iterator<Container,Function>'

the items I'm iterating over are not mutable. Anyone know how to tackle this issue?

+3  A: 

You can use transform instead:

transform(src.begin(), src.end(), back_inserter(container), func);

Note that const applied on a reference type is a no-op. So if argument_type is T&, then saying const argument_type does not yield back const T& but T& again. So if your source items are constant you would try to bind them to the non-const reference parameter of operator= in case that argument_type is a reference:

typedef int &intr;
const intr& a = 0; // fails - "const" is ignored!
Johannes Schaub - litb
Reached my daily limit of upvotes, will have to come back later to give you a +1.
wheaties