Iterator invalidation

  • What is invalidation rules of QT Container iterators?
    Here said:

    Iterators of both types are invalidated when the data in the container is modified or detached from implicitly shared copies due to a call to a non-const member function.

    I understand this:

    QMap<qint32, QString> myMap;
    myMap[0] = "zero";
    myMap[1] = "one";
    myMap[2] = "two";
    QMap<qint32, QString>::iterator it = myMap.begin();
    myMap[3] = "three";
    ++it;   //error, iterator is invalid after container was modified

    But here said:

    Multiple iterators can be used on the same map. If you add items to the map, existing iterators will remain valid. If you remove items from the map, iterators that point to the removed items will become dangling iterators.

    According to that text, my code is valid and i can remove or add elements to my map without iterator invalidation.
    std::map allows change container without iterator invalidation.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    See the Implicit sharing iterator problem part of the documentation you linked to have a more detailed explanation about what might be going on with Qt's implicitly shared containers.

  • @SGaist thank you for your answer.
    I have read it. Let realize that i have only one container and don`t copy it. Can i use iterator and change container? Or is it a QT rule: don`t use iterator when container can be changed?

  • Lifetime Qt Champion

    You have several examples in the detailed description QMap::iterator that do exactly that.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.