Search code examples
c++c++14const-iterator

Why elements can be inserted in a vector when using const_iterators


Considering the code below,

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main(){
    vector<int> value{22, 23, 25, 34, 99};
    auto it = find(value.cbegin(), value.cend(), 25);
    value.insert(it, 77);
    return 0;
}

Here it is a const_iterator. Before the insertion, it points to 25. After the insertion, it points to 77. Wouldn't this be considered a modification?


Solution

  • A const_iterator prevents you from modifying the element that iterator points to, it does not prevent you from modifying the container itself.

    In your example you're finding an iterator to the element 25, and inserting 77 before 25. You're not modifying the value 25.

    Before the insertion, it points to 25. After the insertion, it points to 77.

    vector::insert always invalidates the iterators at and after the point of insertion. So if you dereference it in your example after insert, it's undefined behavior. Instead you could do

    it = value.insert(it, 77);
    // it points to 77, the newly inserted element
    // (it + 1) points to 25