I have to refactor old code that looks like this (I am not a very proficient C++ coder)
std::set<SomeObject>::iterator it = setobject.begin();
do {
it->setProperty1ToNextValue();
it->getProperty2();
it->getProperty3();
it++
} while (it != setobject.end());
Basically I want to iterate through the elements of the set and get and set/update some of their properties. I cant use the original set since I run in the problems described in this thread the object has type qualifiers that are not compatible with the member function object type is const
I am thinking of replacing the set with a dequeue (it will involve some rewriting) since I will then be able to set and get properties on each element of the dequeue. Is this a good approach?
A
std::set
works by keeping all the items in order according to the object's<
operator. The reason you cannot call non-const methods on your object is because there is risk that those methods will change the value returned by your objects<
operator, and therefore effectively "reorder" the set under the hood without thestd::set
knowing.While you haven't specified enough of what you are trying to do for us to provide the best answer, here is a couple ways to technically achieve calling some methods on your set. You can use
const_cast
to call methods you are sure won't modify the key. Or you can put the items in a vector, call methods that might modify the "key", and then put them back in the original set.