Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why STL containers can insert using const iterator

Why STL containers can insert using const_iterator? For example, there is

iterator std::list::insert (const_iterator position, const value_type& val);

I have thought that const_iterator's does not allow to modify container.

like image 935
se0808 Avatar asked Feb 11 '23 19:02

se0808


2 Answers

When an element is inserted into a list, the other elements are not modified. The iterator is only used to determine the insertion position, not to modify (= call non-const member function on) any of the existing elements.

Even erase can take a const_iterator. Again, this is because erasing an element does not modify it, either. This may sound strange, but it's trivial if you consider this:

void f()
{
    std::string const s = "foo";
    // the function ends and s is destroyed even though it was constant
}
like image 191
Christian Hackl Avatar answered Feb 20 '23 11:02

Christian Hackl


They are called const_iterators because they don't allow you to change underlying value, not the container itself. You still need to have a non-const list to insert elements to, because insert is a non-const member of std::list, but the interface is made in the least restricting way.

Consider that you have a function that lets you find and iterator to some element. It doesn't need to change anything, so you design it to return const_iterator. And then you want to insert to list at this iterator, but you wouldn't be able to, if the interface for the list was more restricted then it is.

like image 44
JustSomeGuy Avatar answered Feb 20 '23 11:02

JustSomeGuy