Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions

TQMap Class Reference

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

#include <tqmap.h>

List of all member functions.

Public Members

Protected Members

Related Functions


Detailed Description

The TQMap class is a value-based template class that provides a dictionary.

TQMap is a TQt implementation of an STL-like map container. It can be used in your application if the standard map is not available on all your target platforms. TQMap is part of the TQt Template Library.

TQMap<Key, Data> defines a template instance to create a dictionary with keys of type Key and values of type Data. TQMap does not store pointers to the members of the map; instead, it holds a copy of every member. For this reason, TQMap is value-based, whereas TQPtrList and TQDict are pointer-based.

TQMap contains and manages a collection of objects of type Data with associated key values of type Key and provides iterators that allow the contained objects to be addressed. TQMap owns the contained items.

Some classes cannot be used within a TQMap. For example everything derived from TQObject and thus all classes that implement widgets. Only values can be used in a TQMap. To qualify as a value, the class must provide

Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases, this is sufficient.

The class used for the key requires that the operator< is implemented to define ordering of the keys.

TQMap's function naming is consistent with the other TQt classes (e.g., count(), isEmpty()). TQMap also provides extra functions for compatibility with STL algorithms, such as size() and empty(). Programmers already familiar with the STL map can use these the STL-like functions if preferred.

Example:

    #include <ntqstring.h>
    #include <tqmap.h>
    #include <ntqstring.h>

    class Employee
    {
    public:
        Employee(): sn(0) {}
        Employee( const TQString& forename, const TQString& surname, int salary )
            : fn(forename), sn(surname), sal(salary)
        { }

        TQString forename() const { return fn; }
        TQString surname() const { return sn; }
        int salary() const { return sal; }
        void setSalary( int salary ) { sal = salary; }

    private:
        TQString fn;
        TQString sn;
        int sal;
    };

    int main(int argc, char **argv)
    {
        TQApplication app( argc, argv );

        typedef TQMap<TQString, Employee> EmployeeMap;
        EmployeeMap map;

        map["JD001"] = Employee("John", "Doe", 50000);
        map["JW002"] = Employee("Jane", "Williams", 80000);
        map["TJ001"] = Employee("Tom", "Jones", 60000);

        Employee sasha( "Sasha", "Hind", 50000 );
        map["SH001"] = sasha;
        sasha.setSalary( 40000 );

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

Program output:

    JD001: Doe, John earns 50000
    JW002: Williams, Jane earns 80000
    SH001: Hind, Sasha earns 50000
    TJ001: Jones, Tom earns 60000
    

The latest changes to Sasha's salary did not affect the value in the list because the map created a copy of Sasha's entry. In addition, notice that the items are sorted alphabetically (by key) when iterating over the map.

There are several ways to find items in a map. The begin() and end() functions return iterators to the beginning and end of the map. The advantage of using an iterator is that you can move forward or backward by incrementing/decrementing the iterator. The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the map it belongs to, however it is not dereferenceable; operator*() will not return a well-defined value. If the map is empty, the iterator returned by begin() will equal the iterator returned by end().

Another way to find an element in the map is by using the find() function. This returns an iterator pointing to the desired item or to the end() iterator if no such element exists.

Another approach uses the operator[]. But be warned: if the map does not contain an entry for the element you are looking for, operator[] inserts a default value. If you do not know that the element you are searching for is really in the list, you should not use operator[]. The following example illustrates this:

        TQMap<TQString,TQString> map;
        map["Clinton"] = "Bill";
        str << map["Clinton"] << map["Bush"] << endl;
    

The code fragment will print out "Clinton", "". Since the value associated with the "Bush" key did not exist, the map inserted a default value (in this case, an empty string). If you are not sure whether a certain element is in the map, you should use find() and iterators instead.

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

It is safe to have multiple iterators at the same time. If some member of the map is removed, only iterators pointing to the removed member become invalid; inserting in the map does not invalidate any iterators.

Since TQMap is value-based, there is no need to be concerned about deleting items in the map. The map holds its own copies and will free them if the corresponding member or the map itself is deleted.

TQMap is implicitly shared. This means you can just make copies of the map in time O(1). If multiple TQMap instances share the same data and one is modifying the map's data, this modifying instance makes a copy and modifies its private copy: so it does not affect other instances. If a TQMap is being used in a multi-threaded program, you must protect all access to the map. See TQMutex.

There are a couple of ways of inserting new items into the map. One uses the insert() method; the other uses operator[]:

    TQMap<TQString, TQString> map;
    map["Clinton"] = "Bill";
    map.insert( "Bush", "George" );
    

Items can also be removed from the map in several ways. One way is to pass an iterator to remove(). Another way 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 TQMapIterator, TQt Template Library Classes, Implicitly and Explicitly Shared Classes, and Non-GUI Classes.


Member Type Documentation

TQMap::ConstIterator

The map's const iterator type, TQt style.

TQMap::Iterator

The map's iterator type, TQt style.

TQMap::ValueType

Corresponds to TQPair<key_type, mapped_type>, TQt style.

TQMap::const_iterator

The map's const iterator type.

TQMap::const_pointer

Const pointer to value_type.

TQMap::const_reference

Const reference to value_type.

TQMap::iterator

The map's iterator type.

TQMap::key_type

The map's key type.

TQMap::mapped_type

The map's data type.

TQMap::pointer

Pointer to value_type.

TQMap::reference

Reference to value_type.

TQMap::size_type

An unsigned integral type, used to represent various sizes.

TQMap::value_type

Corresponds to TQPair<key_type, mapped_type>.

Member Function Documentation

TQMap::TQMap ()

Constructs an empty map.

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

Constructs a copy of m.

This operation costs O(1) time because TQMap is implicitly shared. This makes returning a TQMap from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and this takes O(n) time.

TQMap::TQMap ( const std::map<Key, T> & m )

Constructs a copy of m.

TQMap::~TQMap ()

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

iterator TQMap::begin ()

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

The items in the map are traversed in the order defined by operator<(Key, Key).

See also end() and TQMapIterator.

const_iterator TQMap::begin () const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

See also end() and TQMapConstIterator.

void TQMap::clear ()

Removes all items from the map.

See also remove().

const_iterator TQMap::constBegin () const

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

The items in the map are traversed in the order defined by operator<(Key, Key).

See also constEnd() and TQMapConstIterator.

const_iterator TQMap::constEnd () const

The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the map it belongs to, but it is not dereferenceable; operator*() will not return a well-defined value.

This iterator equals constBegin() if the map is empty.

See also constBegin() and TQMapConstIterator.

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

Returns TRUE if the map contains an item with key k; otherwise returns FALSE.

size_type TQMap::count ( const key_type & k ) const

Returns the number of items whose key is k. Since TQMap does not allow duplicate keys, the return value is always 0 or 1.

This function is provided for STL compatibility.

size_type TQMap::count () const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns the number of items in the map.

See also isEmpty().

void TQMap::detach () [protected]

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

bool TQMap::empty () const

Returns TRUE if the map contains no items; otherwise returns FALSE.

This function is provided for STL compatibility. It is equivalent to isEmpty().

See also size().

iterator TQMap::end ()

The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the map it belongs to, but it is not dereferenceable; operator*() will not return a well-defined value.

This iterator equals begin() if the map is empty.

See also begin() and TQMapIterator.

const_iterator TQMap::end () const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

void TQMap::erase ( iterator it )

Removes the item associated with the iterator it from the map.

This function is provided for STL compatibility. It is equivalent to remove().

See also clear().

void TQMap::erase ( const key_type & k )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Removes the item with the key k from the map.

iterator TQMap::find ( const Key & k )

Returns an iterator pointing to the element with key k in the map.

Returns end() if no key matched.

See also TQMapIterator.

const_iterator TQMap::find ( const Key & k ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns an iterator pointing to the element with key k in the map.

Returns end() if no key matched.

See also TQMapConstIterator.

iterator TQMap::insert ( const Key & key, const T & value, bool overwrite = TRUE )

Inserts a new item with the key, key, and a value of value. If there is already an item whose key is key, that item's value is replaced with value, unless overwrite is FALSE (it is TRUE by default). In this case an iterator to this item is returned, else an iterator to the new item is returned.

TQPair<iterator, bool> TQMap::insert ( const value_type & x )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Inserts the (key, value) pair x into the map. x is a TQPair whose first element is a key to be inserted and whose second element is the associated value to be inserted. Returns a pair whose first element is an iterator pointing to the inserted item and whose second element is a bool indicating TRUE if x was inserted and FALSE if it was not inserted, e.g. because it was already present.

See also replace().

bool TQMap::isEmpty () const

Returns TRUE if the map contains no items; otherwise returns FALSE.

See also count().

TQValueList<Key> TQMap::keys () const

Returns a list of all the keys in the map, in order.

TQMap<Key, T> & TQMap::operator= ( const TQMap<Key, T> & m )

Assigns m to this map and returns a reference to this map.

All iterators of the current map become invalidated by this operation. The cost of such an assignment is O(1), because TQMap is implicitly shared.

TQMap<Key, T> & TQMap::operator= ( const std::map<Key, T> & m )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Assigns m to this map and returns a reference to this map.

All iterators of the current map become invalidated by this operation.

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

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

You can use this operator both for reading and writing:

    TQMap<TQString, TQString> map;
    map["Clinton"] = "Bill";
    stream << map["Clinton"];
    

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

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Warning: This function differs from the non-const version of the same function. It will not insert an empty value if the key k does not exist. This may lead to logic errors in your program. You should check if the element exists before calling this function.

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

void TQMap::remove ( iterator it )

Removes the item associated with the iterator it from the map.

See also clear().

void TQMap::remove ( const Key & k )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Removes the item with the key k from the map.

iterator TQMap::replace ( const Key & k, const T & v )

Replaces the value of the element with key k, with the value v.

See also insert() and remove().

size_type TQMap::size () const

Returns the number of items in the map.

This function is provided for STL compatibility. It is equivalent to count().

See also empty().

TQValueList<T> TQMap::values () const

Returns a list of all the values in the map, in key order.


Related Functions

TQDataStream & operator<< ( TQDataStream & s, const TQMap<Key, T> & m )

Writes the map m to the stream s. The types Key and T must implement the streaming operator as well.

TQDataStream & operator>> ( TQDataStream & s, TQMap<Key, T> & m )

Reads the map m from the stream s. The types Key and T must implement the streaming operator as well.


This file is part of the TQt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved.


Copyright © 2007 TrolltechTrademarks
TQt 3.3.8