Is it right to go through QMap using iterators and erase / add items?

Is it right to go through QMap using iterators and do the following: delete some elements and add new ones?

For instance:

for( QMap<key_t,val_t>::iterator it = map.begin(); it != map.end(); ++it ) { if( it->value == something ) { map.erase(it); map.insert(it->key+10,it->value); } } 

It seems that nothing will be done wrong, I ask you to be sure. (I do not have enough time to check this).

UPD Solve with QMap::unite() :

 for( QMap<key_t,val_t>::iterator it = map.begin(); it != map.end(); ++it ) { if( it->value == something ) { tmp_map.insert(it->key+10,it->value); map.erase(it); } } map.unite(tmp_map); 

Thanks for answers!

+6
source share
4 answers

Think about it a little ... You iterate through the collection, removing the element in the middle and adding another item to another location. Will iterators be correct? Will the next β€œiterator” be the next item?

In general, it is not recommended to change the collection that you iterate. If you then need to use the temporary collection and copy the selected items to it, clear the real collection and move the elements from the temporary collection to the real one.

In your case, however, why not use QMap::find to search for something , and if it is found, delete it and add a new element and loop it until something no longer found?

+4
source

The iterator will not be valid erase , therefore it cannot be used safely or increased. The following should work:

 for( QMap<key_t,val_t>::iterator it = map.begin(); it != map.end(); ) { if( it->value == something ) { map.insert(it.key()+10,it.value()); it = map.erase(it); } else { ++it; } } 
+13
source

I would expect it be invalid after map.erase(it) , in which case it->value and ++it will not work.

+2
source

You must "reset" use your iterator for the returned erase and insert . This is basically the principle.

+1
source

Source: https://habr.com/ru/post/906669/


All Articles