Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
Milo Lu Avatar asked Feb 11 '18 03:02

Milo Lu


People also ask

What method can you use to insert elements to the vector numbers?

The insert() method can be used to insert single or multiple elements into a given vector in different ways, for different cases. We can insert a single value at our desired position, we can even insert multiple values into the vector at once, and even we can insert a bunch of values from another vector to it.

How do you enter elements into vectors?

To add elements to vector, you can use push_back() function.

How do you add an element to a vector at a specific position?

std::vector::insert() is a built-in function in C++ STL that inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.

Can we add element in vector from front?

It works alot like a std::vector but you can add and remove items from both the front and the end. It does this by dividing the internal storage up into smaller blocks.


2 Answers

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
like image 103
Praetorian Avatar answered Oct 07 '22 10:10

Praetorian


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
like image 25
haccks Avatar answered Oct 07 '22 11:10

haccks