1.QMap
有时候回遇见在循环中需要删除某个map元素的操作,如果直接remove其实会影响内部迭代器,这样操作会有问题。删除方式换为erase并更新迭代器即可
for (auto it = map.begin(); it != map.end();)
if (it.value() % 2 == 1)
it = map.erase(it);
else
++it;
这里之所以安全的原因是erase已经是下一个成员了,根据文档说明,erase会返回下一个成员的迭代器
Removes the (key, value) pair pointed to by the iterator pos from the map, and returns an iterator to the next item in the map.
上面的是STL-style iterators的写法,qmap同时也提供了Java-style iterators的写法
QMutableMapIterator<QString, QString> i(map);
while (i.hasNext()) {
i.next();
if (i.key() == i.value())
i.remove();
}
java的看起来更方便,但是效率会稍微低一点
The Java-style iterators are more high-