More Related Content
Similar to Issue 1 Abusing Q Map
Similar to Issue 1 Abusing Q Map (20)
Issue 1 Abusing Q Map
- 1. 本页已使用福昕阅读器进行编辑。
Trolltech | Documentation | Qt Quarterly | Seriously Weird QRegExp »
福昕软件(C)2005-2009,版权所有,
仅供试用。
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" );
Copyright © 2002 Trolltech. Trademarks Seriously Weird QRegExp »