How does back_inserter work?
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,
ChanThey 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;
}
back_inserter()
returns a back_insert_iterator
, which has to function like an output iterator. Specifically, it has to support operations such as pre- and post increment, and dereference assignment.
If it didn't support those operations, it couldn't be used where output iterators are required.
精彩评论