I have a func as below:
class Book
{
...
set<Level> sLevels ;
...
};
void Book::del_order (Order *ord) {
if ( ord && del_oid(ord))
{ // it's in there somewhere
set<Level>::iterator it=sLevels.find(Level(ord)) ;
if ( it!=sLevels.end())
{
it->del_order(ord) ;
}
else
{
DEBUG("ERROR:del_order:can't find the order to delete") ;
}
}
delete ord ;
}
...
}
When compiling, i'm getting:
book.h: In member function `void Book::del_order(Order*)':
book.h:38: passing `const Level' as `this' argument of `void
Level::del_order(Order*)' discards qualifiers
The problem is ord is not const, "it" is not const, sLevels is not const, so what am I missing? Thank you.
The error message is informing you that your iterator is a const_iterator. This comes as a surprise because you are not explicitly defining it as such, right?
Here's the deal: std::set is an associative container. Associative containers associate a key with each value and they are stored sorted the key. In the case of a set (rather than a map) the key IS the value. If you were to modify the key, the container would have to be notified to re-sort itself (in order to maintain its efficiency guarantees for look ups, which are logarithmic). To prevent that situation the container forces the key to be constant--so you cannot modify an element in place in a set. You would have to remove it, modify it, and insert it.
set iterators are always const_iterators. Since they're generally binary search trees, it wouldn't do for the user to modify the values and thus breaking its order. Updating an element requires an erase + insert.
you guys are great. this answers my other question about the foundamental different between set and map. I always thought why use map when i can just group the key and value into a new struct and use set.
btw, where did you get such info. I couldn't find anything like this.
Generic Programming and the STL by Austern. It covers the STL from top to bottom without being too technical. Insight into design goals and implementation is given only when beneficial. I highly recommend it.