12

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?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Milo Lu
  • 3,176
  • 3
  • 35
  • 46
  • 5
    you aren't modifying the vector via the iterator, `value` (which is not const) is modifying itself – kmdreko Feb 11 '18 at 03:37
  • 1
    Note that `vector::insert` and `vector::erase` (or, for that matter, corresponding methods of other standard containers) only accept `const_iterator` since C++11. I.e. there was probably a proposal that made it into C++11, and which gives a rationale for the change. – Arne Vogel Feb 11 '18 at 19:46

2 Answers2

13

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
Praetorian
  • 106,671
  • 19
  • 240
  • 328
1

cosnt_iterator points to const value. It means when you dereference it then it will return const object. The iterator can be modified but not the object that iterator points to.

vector<int> value{22, 23, 25, 34, 99};
std::vector<int>::const_iterator it = find(value.cbegin(), value.cend(), 25);
it = value.insert(it, 77); // valid 
*it = 77;                  // Error

Think is like pointer to const objects. When you declare

int const a = 10;
int const *ptr = &a;

then ptr can be modified but the object ptr is pointing to shall not.

*ptr = 5         // Error
int const b = 0;
ptr = &b;        // Valid
haccks
  • 104,019
  • 25
  • 176
  • 264