Trolltech | Documentation | Qt Quarterly | Seriously Weird QRegExp »

Abusing QMap

The QMap<Key, Value> class stores (key, value) pairs where each key is associated with a single value. This article presents a quick-and-dirty trick to make keys work with multiple values.

The basic idea is to replace the Value type with a more complex type, such as QValueList<Value>, like this:

    QMap<QString, QStringList> map;

(QStringList is an enhanced QValueList<QString>.) Inserting a value into a "multi-map" is simple:

    map["presidents"].append( "George Washington" );

If the multi-map map already contains a "presidents" key, map[presidents] returns a reference to the QStringList that corresponds to it; otherwise, an empty QStringList is automatically created.

The other operations -- testing the presence of a (key, value) pair and removing a (key, value) pair -- are just as easy:

    if ( map["presidents"].contains("Bill Clinton") )
	map["presidents"].remove( "Ronald Reagan" );

The remove() operation above will remove the pair ("presidents", "Ronald Reagan") from the map if the map contains it; otherwise it will do nothing. We can even insert the same (key, value) pair many times:

    map["presidents"].append( "George Bush" );
    map["presidents"].append( "George Bush" );

Removing one of them is straightforward:

    map["presidents"].remove(
        map["presidents"].find("George Bush") );

In programming, as in politics, duplicate values aren't always welcome. They can easily be avoided in the first place:

    if ( !map["presidents"].contains("John Adams") )
	map["presidents"].append( "John Adams" );

And they can easily be removed entirely:

    map["presidents"].remove( "John Adams" );


This document is licensed under the Creative Commons Attribution-Share Alike 2.5 license.

Copyright © 2002 Trolltech. Trademarks Seriously Weird QRegExp »