Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does back_inserter work?

Tags:

c++

stl

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

like image 201
Chan Avatar asked Jan 19 '11 08:01

Chan


People also ask

What does back inserter do?

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.

Why use back_ inserter c++?

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.

What is std :: inserter?

A std::insert_iterator which can be used to insert elements into the container c at the position indicated by i .


2 Answers

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;
like image 161
Anycorn Avatar answered Oct 06 '22 10:10

Anycorn


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;
}
like image 32
Yakov Galka Avatar answered Oct 06 '22 10:10

Yakov Galka