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?
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.
To add elements to vector, you can use push_back() function.
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.
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.
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 to25
. After the insertion, it points to77
.
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
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
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