PDA

View Full Version : How to use QMap::remove() to delete some item?



jedychen
17th September 2008, 04:58
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??
}

aamer4yu
17th September 2008, 05:54
Remove takes key as argument, so I guess it should be map.remove(it.key());

jedychen
17th September 2008, 10:16
I want ask: use remove() in for(){},maybe wrong, this function will change the iterator's order. So I maybe cannot trival all items!

caduel
17th September 2008, 10:39
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

jedychen
18th September 2008, 02:14
unfortunately, I use Qt 3.3.8.I cannot find any functions to get dangling iterators.-_-

caduel
18th September 2008, 08:29
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;
}