Instead, use QMap::erase
, which returns an iterator to the element next to the one you just deleted:
for (auto it = map.begin(); it != map.end();) if (it.value() % 2 == 1) it = map.erase(it); else ++it;
Another way is to use the postfix increment operator on the iterator:
for (auto it = map.begin(); it != map.end();) if (it.value() % 2 == 1) map.erase(it++); else ++it;
Another way (and probably less efficient) is to use the STL remove_copy_if
algorithm, followed by swap
:
bool valueIsOdd(int value) {return value % 2 == 1;} QMap<int,int> b; std::remove_copy_if(a.begin(), a.end(), std::inserter(b, b.end()), &valueIsOdd); a.swap(b);
I can not check the last example at the moment.
source share