简体   繁体   中英

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

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?

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 multiple items with key key, this function returns a reference to the most recently inserted value.

(emphasis mine)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM