How to use QMap::remove() to delete some item?
Code:
QMap<int, QString> mapCity;
mapCity.insert(1,"one");
mapCity.insert(2,"two");
...
mapCity.insert(9,"nine");
...
//Now, I want delete 1,2,3.
QMap<int, QString>::Iterator it;
for( it = mapCity.begin(); it != mapCity.end(); ++it)
{
if( it.key() < 4 )
mapCity.remove( it ); //Is that OK??
}
Re: How to use QMap::remove() to delete some item?
Remove takes key as argument, so I guess it should be map.remove(it.key());
Re: How to use QMap::remove() to delete some item?
I want ask: use remove() in for(){},maybe wrong, this function will change the iterator's order. So I maybe cannot trival all items!
Re: How to use QMap::remove() to delete some item?
Assuming you use Qt4, try QMutableMapIterator instead.
(With the 'classic' STL style iterator you will get dangling iterators if you remove the item an iterator points to. Java style iterators are easier to use (correctly) imo.)
HTH
Re: How to use QMap::remove() to delete some item?
unfortunately, I use Qt 3.3.8.I cannot find any functions to get dangling iterators.-_-
Re: How to use QMap::remove() to delete some item?
Code:
QMap<int, QString>::Iterator it;
for( it = mapCity.begin(); it != mapCity.end(); ) // remove increment here
{
if( it.key() < 4 )
mapCity.remove( it++ ); // this is ok; note POSTFIX operator here
else
++it;
}