Unobvious behavior of the QMap().begin() function in Qt C++

234 Views Asked by At

Let's look at the simple code with QMap iterator.

#include <QMap>
#include <QDebug>

int main()
{
    QMap<int, QMap<int, int>> testA;
    testA [0][0] = 1;

    QMap<int,int>::iterator _iterTestA;

    for(_iterTestA = testA[1].begin(); _iterTestA!= testA[1].end(); _iterTestA++){
        qDebug()<<"Why am I working!? ";
    }

    qDebug()<<" testA " << testA;

}

Expected behavior

Code raise with some kind of error when trying to set an iterator to a non-existence element of QMap.

Real behavior

Qt just creating an element testA[1] with an empty QMap() inside.

So output is:

testA  QMap((0, QMap((0, 1)))(1, QMap()))

What happening and why Qt is makes the decision for me?

1

There are 1 best solutions below

4
eyllanesc On

That behavior is fully documented:

T &QMap::operator[](const Key &key)
Returns the value associated with the key key as a modifiable reference.

If the map contains no item with key key, the function inserts a default-constructed value into the map with key key, and returns a reference to it. If the map contains multiple items with key key, this function returns a reference to the most recently inserted value.

(emphasis mine)