Qt logo

QMap Class Reference


The QMap class is a value based template class that provides a dictionary More...

#include <qmap.h>

List of all member functions.

Public Members

Protected Members

Related Functions

(Note that these are not member functions.)

Detailed Description

The QMap class is a value based template class that provides a dictionary

Define a template instance QMap<Key,Data> to create a dictionary with keys of type X and values of type Y. Please notice that QMap does not store pointers to the members of the map. It holds a copy of every member. That is the reason why this kind of classes are called "value based" while QList and QDict are "reference based".

Some classes can not be used within a QMap. For example everything derived from QObject and as a reason of this that extends to all classes which implement widgets. You can only put stuff in a QMap which can be easily copied. That means that the class X and Y must implement a copy constructor.

Example:

    #include <qmap.h>
    #include <qstring.h>
    #include <stdio.h>

    class Employee
    {
    public:
        Employee( const QString& name, int salary ) { n=name; s=salary; }
        Employee( const Employee& _e ) { n = _e.name; s = _e.s; }

        QString     name()   const               { return n; }
        int         salary() const               { return s; }
        void        setSalary( int _s ) const    { s = _s; }
    private:
        QString     n;
        int         s;
    };

    void main()
    {
        typedef QMap<QString,Employee> EmployeeMap;
        EmployeeMap map;                // map of Employee

        map.insert( "Gates", Employee("Bill", 50000) );
        map.insert( "Ballmer", ( Employee("Steve",80000) );
        map.insert( "Sommer," ( Employee("Ron",  60000) );

        Employee joe( "Joe", 50000 );
        map.insert( "Doe", joe );
        joe.setSalary( 4000 );

        EmployeeMap::Iterator it;
        for( it = map.begin(); it != map.end(); ++it )
            printf( "%s, %s earns %d\n", it.key(), it.data().name(), it.data().salary() );
    }

Program output:

        Ballmer, Steve earns 80000
        Doe, Joe earns 50000
        Gates, Bill earns 50000
        Sommer, Ron earns 60000

As you can see, the latest changes to Joe's salary did not affect the value in the list because the map created a copy of Joe's entry. In addition you should notice that the items are alphabetically sorted when iterating over the map.

There are two ways to find values in the list. The first one is to use the find() function. It returns an iterator pointing to the desired item or the end() iterator it no such element exists.

The second approach uses the operator[]. But be warned: If you don't know that the element you are searching for is really in the list, then you should not use operator[]. The following example illustrates that.

        QMap<QString,QString> map;
        map.insert( "Weis", "Torben" );
        str << map["Weis"] << map["Ettrich"] << endl;

        const QMap<QString,QString>& map2 = map;
        str << map["Weis"] << map["Reggie"] << endl;

The code fragment will print out "Weis", "" and the second part will print "Weis", "". In addition the first fragment inserted an empty entry with key "Ettrich". The second one did not insert an empty entry with key "Reggie" because the const operator[] was used which can not do insertion. So if you are not sure whether a certain element is in the map you should use find() and iterators.

If you just want to know whether a certain key is contained in the map, the the contains() function is what you are looking for. In addition count() tells you how many keys there are currently in the map.

Another method for traversing a map is to use the functions begin() and end(). With a simple for loop as shown in the example you can iterate over the complete map. It is save to have multiple iterators at the same time. If some member of the map is removed then only iterators pointing to the removed member become invalid. Inserting in the map does not invalidate any iterator.

Since QMap is value based there is no need to care about deleting elements in the list. The list holds its own copies and will free them if the corresponding member or the list itself is deleted. You can force the list to free all of its item with clear().

QMap is implicitly shared. This means you can just make copies of the map in time O(1). If multiple QMap instances share the same data and one is modifying the map's data then this modifying instance makes a copy and modifies its private copy - thus it does not affect other instances. From a developer's point of view you can think that a QMap and a copy of this map have nothing to do with each other.

There are two ways of inserting new elements in a list. One uses the insert() method while the other one uses operator[] like this:

        QMap<QString,QString> map;
        map["Weis"] = "Torben";
;

Items can be removed from the map in two ways. The first is to pass an iterator to the remove(). The other possibility is to pass a key value to remove() which will delete the entry with the requested key. In addition you can clear the entire map using the clear() method.

See also: QMapIterator.


Member Function Documentation

QMap::QMap ()

Constructs an empty map.

QMap::QMap ( const QMap<Key,T> & m )

Constructs a copy of m.

This operation costs O(1) time since QMap is implicit shared. The first instance applying modifications to a shared list will create a copy which takes in turn O(n) time. However returning a QMap from a function is very fast.

QMap::~QMap ()

Destroys the map. References to the values in the map and all iterators of this map become invalidated. Since QMap is highly tuned for performance you won't see warnings if you use invalid iterators, because it is impossible for an iterator to check whether it is valid or not.

ConstIterator QMap::begin () const

Returns an iterator pointing to the first element in the map. This iterator equals end() if the map is empty;

See also: end(), \sa and QMapConstIterator.

Iterator QMap::begin ()

Returns an iterator pointing to the first element in the map. This iterator equals end() if the map is empty;

See also: end(), \sa and QMapIterator.

void QMap::clear ()

Removes all items from the map.

See also: remove().

bool QMap::contains ( const Key & k ) const

Returns TRUE if the key \k is contained in the map.

uint QMap::count () const

Returns the number of items in the ap.

See also: isEmpty().

void QMap::detach () [protected]

If the map does not share its data with another QMap instance, then nothing happens, otherwise the function creates a new copy of this data and detaches from the shared one. This function is called whenever the map is modified. The implicit sharing mechanism is implemented this way.

ConstIterator QMap::end () const

Returns an iterator pointing behind the last element in the map. This iterator equals begin() if the map is empty.

See also: begin(), \sa and QMapConstIterator.

Iterator QMap::end ()

Returns an iterator pointing behind the last element in the map. This iterator equals begin() if the map is empty.

See also: begin(), \sa and QMapIterator.

ConstIterator QMap::find ( const Key & k ) const

Finds the key k in the map.

Returns end() if no key did match.

See also: QMapConstIterator.

Iterator QMap::find ( const Key & k )

Finds the key k in the map.

Returns end() if no key did match.

See also: QMapIterator.

Iterator QMap::insert ( const Key & key, const T & value )

Inserts the value with key k.

Returns an iterator pointing at the inserted value.

See also: QMapIterator.

bool QMap::isEmpty () const

Returns TRUE if the list is empty, i.e. count() == 0. Returns FALSE otherwise.

See also: count().

T& QMap::operator[] ( const Key & k )

Returns the value associated with the key k. If no such key is present then en empty item is inserted with this key and a reference to the item is returned.

You can use this operator in two directions: For reading and for writing:

        QMap<QString,QString> map;
        map[ "Weis" ] = "Torben";
        stream << map[ "Weis" ];

const T& QMap::operator[] ( const Key & k ) const

Returns the value associated with the key k. If no such key is present then a reference to an empty item is returned.

void QMap::remove ( Iterator it )

Removes the item at position it in the map.

See also: clear(), \sa and QMapIterator.

void QMap::remove ( const Key & k )

Removes the item with the key k.

See also: clear().

Iterator QMap::replace ( const Key & k, const T & v )

Replaces the value with key k from the map if possible and inserts the new value v with key \k in the map.

See also: insert(), \sa, remove(), \sa and QMapIterator.


Related Functions

QDataStream& operator>> (QDataStream & s, QMap<Key,T> & m)

Reads a map from the stream. The types Key and T must implement the streaming operator, too.

QDataStream& operator<< (QDataStream & s, const QMap<Key,T> & m)

Writes a map to the stream. The types Key and T must implement the streaming operator, too.


Search the documentation, FAQ, qt-interest archive and more (uses www.troll.no):


This file is part of the Qt toolkit, copyright © 1995-99 Troll Tech, all rights reserved.


Copyright © 1999 Troll TechTrademarks
Qt version 2.0.2