8

I want to change the element in a set, so I used set<T>::iterator. However, the compiler argues "the element is const". Then I realized that set<T>::iterator is a const_iterator...

So, how I can change the element? Erase it and then insert a new one?

jogojapan
  • 68,383
  • 11
  • 101
  • 131
Eric.Q
  • 703
  • 1
  • 9
  • 21

3 Answers3

21

The elements of the set will be in sorted order. If you are allowed to modify an element, then this sorting order can not be maintained. Hence you can not modify the item. You need to erase the existing element and insert a new one.

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • 7
    It should be mentioned, though, that some changes to an element do not affect how it's sorted. If you want to make a change that you are sure does not impact the sorting order, there is always `const_cast` as a last resort. Risky and not beautiful, but nevertheless. – jogojapan Mar 07 '12 at 11:52
  • thanks.I know that . So this is the only way to modify the element? – Eric.Q Mar 07 '12 at 11:57
  • 2
    Since `erase` doesn't throw unless the user code it calls throws, it's probably better to insert the new element and then erase the old one. That gives you a chance of the strong exception guarantee. – Steve Jessop Mar 07 '12 at 11:57
  • std::unordered_set ..first time to hear that – Eric.Q Mar 07 '12 at 11:59
1

Set elements are constant and may not be modified in place. Modification could change the ordering predicate without changing the position of the element which would violate the constraints of the data structure.

However now in the future (C++17), modifying the element without erasure is possible with the extract member function:

std::set<std::string> stringset{"a", "b", "c"};
auto node = stringset.extract(stringset.begin());
std::string& str = node.value();
str = "d";
stringset.insert(std::move(node));

There is still the cost of list operations but the object itself is not destroyed or copied.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

EDIT: You cant add an element to a specific location in set. the set should be in the sorted order whatever operations you do. So you have to erase the specific element and insert the new element so that the ordering of set isnt lost.

Also read more about set!

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112