[Development] Is QMap Broken

Robert Knight robertknight at gmail.com
Thu Nov 6 15:24:25 CET 2014


> Consider the following program, shouldn't the end() iterator place each
key at the end of the newly created QMap. Instead, the keys and subsequent
iterations are sorted (somehow).

Yes, that's the whole point of a QMap. If you don't care about the order of
elements in a map, you should almost always use a hash (std::unordered_map
or QHash), it is much faster - O(1) vs O(log(n)) for insertion and lookup.

If you want a data structure that combines fast lookup and remembers the
order of insertion, that is sometimes referred to as an 'ordered map' and
there are implementations around - typically they glue together a linked
list and a hash map.

On 6 November 2014 00:36, Robert Steckroth <robertsteckroth at gmail.com>
wrote:

> Consider the following program, shouldn't the end() iterator place each
> key at the end of the newly created QMap. Instead, the keys and
> subsequent iterations are sorted (somehow).
>
> #include <QCoreApplication>
>
>
> #include <QMap>
>
> #include <QString>
>
> #include <QDebug>
>
>
> int main(int argc, char *argv[])
>
> {
>
>     QCoreApplication a(argc, argv);
>
>
>     QMap <QString, QString> m;
>
>
>     m.insertMulti(m.end(), "2", "22");
>
>     m.insertMulti(m.end(), "1", "11");
>
>     m.insertMulti(m.end(), "3", "33");
>
>
>     QMap<QString, QString>::iterator i = m.begin();
>
>     for ( i = m.begin(); i != m.end(); ++i ) {
>
>         qDebug() << ">" << i.key();
>
>     }
>
>
>     qDebug() << ":" << m.keys();
>
>     return a.exec();
>
> }
>
>
> /* OUTPUT:
>
>  *
>
>  * > "1"
>
>  * > "2"
>
>  * > "3"
>
>  * : ("1", "2", "3")
>
>  *
>
>  */
>
>
>
> --
> <surgemcgee>
>
>
>
>
> _______________________________________________
> Development mailing list
> Development at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/development
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20141106/0bd6d588/attachment.html>


More information about the Development mailing list