sort

The QMap object sorts the elements in it by key rather than the order of insert operation.
Let’s see the following example.

#include <iostream>
#include <QMap>
#include <QString>

using namespace std;

int main()
{
    QMap<QString, int> vars;
    vars.insert( "ABD", 1 );
    vars.insert( "ABE", 2 );
    QMapIterator<QString, int> it( vars );
    while ( it.hasNext() )
    {
        it.next();
        cout << it.key().toStdString() << " - " << it.value() << endl;
    }
    return 0;
}

Output:

ABD - 1
ABE - 2

If I change the statement about ABD to the one.

vars.insert( "ABF", 1 );

Output:

ABE - 2
ABF - 1

operator []

The operator[] is very interesting, If the map contains no item with key key, the function inserts a default-constructed value into the map with key key.
So we have to check whether the QMap object has key when we try to read all elements in the container.

#include <iostream>
#include <QMap>
#include <QString>

using namespace std;

int main()
{
    QMap<int, QString> vars;
    vars.insert( 1, "ABF" );
    vars.insert( 2, "ABE" );
    for( int i = 0; i < vars.size(); ++i )
    {
        cout << i << ": " << vars[i].toStdString() << endl;
    }
    return 0;
}

Output:

0: 
1: ABF
2: ABE

To avoid insert (0, "") to the container, we have to check the key firstly.

    for( int i = 0; i < vars.size(); ++i )
    {
        if( vars.contains( i ) )
        {
            cout << i << ": " << vars[i].toStdString() << endl;
        }
    }

Output:

1: ABF

But we can’t read all elements by it, the correct way to read data in the container is to use QMapIterator.

    QMapIterator<int, QString> it( vars );
    while ( it.hasNext() )
    {
        it.next();
        cout << it.key() << " - " << it.value().toStdString() << endl;
    }

Output:

1 - ABF
2 - ABE
Categories: Qt

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page