Search code examples
c++templatesinsert-iterator

How is insert iterator work in c++


there is insert iterator in database template library or other library, Can someone tell me how it work ? Thanks!


Solution

  • It is a template class so you should be able to look it up in the implementation.

    However, the idea is that it stores an iterator (current location) and a reference (pointer) to a container (that is being inserted in). Then it overloads operator= like this:

    insert_iterator& operator= (typename Container::const_reference value)
    {
        m_iter = m_container->insert(m_iter, value);
        ++m_iter;
        return *this;
    }
    

    So it requires a container that supports the insert method and at least a forward iterator, and has the standard typedefs (const_reference or perhaps value_type), so it can declare the right-hand type of its operator=.

    The other output iterator operators (*, ++) just return *this.