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.
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
}
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.
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