I have a problem with what appears to be some sort of implicit casting to const when I use iterators. I’m not really sure which code is relevant (if I did I probably wouldn’t be asking this question!) so I will try my best to illustrate my problem.
typedef set<SmallObject> Container; //not const
void LargeObject::someFunction() { //not const
Container::iterator it; //not const
for (it = c.begin(); it != c.end(); ++it) { //assume c is a "Container"
(*it).smallObjectFunction(); //not a const function
}
}
However I always get the following error:
error: passing 'const SmallObject' as 'this' argument of 'int SmallObject::smallObjectFunction()' discards qualifiers
However, if I cast it as ((SmallObject)(*it).smallObjectFunction(); then I get rid of the error message.
The only thing I can figure is that somehow the definition of
bool operator< (const SmallObject &a) const;
is somehow causing the iterator to return const objects. Any help or explanation here?
Sets and maps keep the elements in order according to the sort condition. For user code not to break invariants, the
keyof the map and the whole element in the set must be constant. Your problem is that the stored element is not aSmallObjectbut aconst SmallObject.If this was not limited you could have:
The problem there is not only that now the set element would not be in order, but that depending on how the tree was built there could be elements that are present in the set but cannot be found.