I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL:
template<class C>
class back_insert_iterator {
protected:
    C* container;
public:
    typedef C                   container_type;
    typedef output_iterator_tag iterator_category;
    typedef void                value_type;
    typedef void                difference_type;
    typedef void                pointer;
    typedef void                reference;
    explicit back_insert_iterator( C& __x ) :container( &__x ) { 
    }
    back_insert_iterator<C>& operator=( const typename C::value_type& val ) { 
        container->push_back( val );
        return *this;
    }
    back_insert_iterator<C>& operator*() {  
        return *this;  
    }
    back_insert_iterator<C>& operator++() {  
        return *this;  
    }
    back_insert_iterator<C>& operator++( int ) {  
        return *this;  
    }
};
I understood most parts, except the last three operator *, ++, ++( int ). My guess for their existence is because they need to support operations when placed inside the STL algorithm. Other than that, I don't know what are they used for? Could anyone help me clarify this?
Thanks,
Chan 
A back-insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at the end of the container.
The back_inserter provides a method in C++ Programming Language that constructs an iterator and does the operation of inserting new elements to a list through the end. Using back_inserter has the advantage that we don't need to have a proper number of the list.
A std::insert_iterator which can be used to insert elements into the container c at the position indicated by i .
They exist because STL algorithms work on iterators which must be post and pre incrementable and have a dereference operator.
try to think what this does:
(*back_inserter) = value;
++back_inserter;
Your guess is correct and there is nothing more than that. It's all about OutputIterator concept. back_insert_iterator is an OutputIterator, that means that it should work with any algorithm that expects OutputIterators. OutputIterator must have these operators defined so algorithms like this could work:
template<class InputIterator, class OutputIterator>
OutputIterator copy(
    InputIterator first, InputIterator last, OutputIterator result)
{
    while(first != last)
        // uses operators =, * and post ++ of OutputIterator.
        *result++ = *first++;
    return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With