Replacing std::list object given an iterator

dbotha picture dbotha · Jul 26, 2011 · Viewed 7.5k times · Source

Given an iterator into a std::list, how do you replace the object at the position that the iterator references? Currently all I can think of is calling insert with the new object and iterator (to insert the new object before the element referenced by the iterator), and then calling erase to remove the object to be replaced. Is there a less roundabout way of accomplishing a replace?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Jul 26, 2011

What's wrong with:

(*it) = obj;

where obj is the replacement value?