Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change element by iterator

Tags:

c++

std

i have problem when i want to change element of set by using iterator. This simple code may explain what i want to do.

  set<int> s;
  s.insert(12);

  set<int>::iterator it = s.begin();
  *it = 4; // error C3892: 'it' : you cannot assign to a variable that is const

Why i can not change value pointed to by normal iterator, not const_iterator?

In my code iterator was return by set::find(). Maybe is better way to pick specific element from set and change him.

like image 554
Scypi Avatar asked Dec 25 '11 01:12

Scypi


People also ask

How do I modify an iterator in C++?

You cannot modify the objects in a container via a const_iterator . If you want to modify the objects, you need to use an iterator (i.e., std::list<Star>::iterator ).

Are sets mutable in CPP?

Modifications that do not break the sorting order are changes in those parts of the contained elements that do not contribute to the sorting order. The C++ Standard does not specify whether the iterator of a set container (type set<T>:: iterator) is a mutable or immutable iterator.


1 Answers

A set is an ordered container (in particular they are implemented as balanced binary search trees). If you were able to change the value of the element through the iterator the order invariant would be broken. Depending on what you are trying to achieve you might be better off with a different container or obtaining the value, removing the element and inserting a new element into the set.

like image 132
David Rodríguez - dribeas Avatar answered Sep 23 '22 11:09

David Rodríguez - dribeas