Can't invoke a non-const method on objects iterated from a std::set

Chris Jefferson caj@cs.york.ac.uk
Sat Oct 30 18:24:00 GMT 2004


Hugues Joly wrote:

>Hi,
>   if I define a set of objects and try to invoke a
>non-const method on each of them while iterating the
>set, I get a compilation error.  The gcc compiler
>complains that I try to invoke a non-constant method
>on a const object.  You can see that in a sample
>program as attachment.
>
>  
>
This is what you should expect according to the standard, and is 
unfortunatly necessary.

If you think about it, the set standard requires that we can find any 
element in logorithmic time, which means that the elements must be kept 
sorted, and also that there are not two elements in the set which are 
equal. If you could alter the elements of the set then it would be 
almost impossible to satisfy these two requirements.

Your have various options. If you want to associate some variable data 
with each key, then you could have each key include a pointer to this 
data (making sure of course you don't make the comparisons functions use 
this data). Alternatively you could use one of the other containers, 
such as set or vector which doesn't have this problem.

Chris



More information about the Libstdc++ mailing list