TQDict Class

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

# TQDict Class Reference

The TQDict class is a template class that provides a dictionary based on TQString keys. More...

`#include <ntqdict.h>`

Inherits TQPtrCollection.

List of all member functions.

## Public Members

- TQDict ( int size = 17, bool caseSensitive = true )
- TQDict ( const TQDict<type> & dict )
- ~TQDict ()
- TQDict<type> & operator= ( const TQDict<type> & dict )
- virtual uint count () const
- uint size () const
- bool isEmpty () const
- void insert ( const TQString & key, const type * item )
- void replace ( const TQString & key, const type * item )
- bool remove ( const TQString & key )
- type * take ( const TQString & key )
- type * find ( const TQString & key ) const
- type * operator[] ( const TQString & key ) const
- virtual void clear ()
- void resize ( uint newsize )
- void statistics () const

## Important Inherited Members

- bool autoDelete () const
- void setAutoDelete ( bool enable )

## Protected Members

- virtual TQDataStream & read ( TQDataStream & s, TQPtrCollection::Item & item )
- virtual TQDataStream & write ( TQDataStream & s, TQPtrCollection::Item ) const

## Detailed Description

The TQDict class is a template class that provides a dictionary based on TQString keys.

TQMap is an STL-compatible alternative to this class.

TQDict is implemented as a template class. Define a template instance TQDict<X> to create a dictionary that operates on pointers to X (X *).

A dictionary is a collection of key-value pairs. The key is a TQString used for insertion, removal and lookup. The value is a pointer. Dictionaries provide very fast insertion and lookup.

If you want to use non-Unicode, plain 8-bit `char*` keys, use the TQAsciiDict template. A TQDict has the same performance as a TQAsciiDict. If you want to have a dictionary that maps TQStrings to TQStrings use TQMap.

The size() of the dictionary is very important. In order to get good performance, you should use a suitably large prime number. Suitable means equal to or larger than the maximum expected number of dictionary items. Size is set in the constructor but may be changed with resize().

Items are inserted with insert(); 0 pointers cannot be inserted. Items are removed with remove(). All the items in a dictionary can be removed with clear(). The number of items in the dictionary is returned by count(). If the dictionary contains no items isEmpty() returns true. You can change an item's value with replace(). Items are looked up with operator[](), or with find() which return a pointer to the value or 0 if the given key does not exist. You can take an item out of the dictionary with take().

Calling setAutoDelete(true) for a dictionary tells it to delete items that are removed. The default behaviour is not to delete items when they are removed.

When an item is inserted, the key is converted (hashed) to an integer index into an internal hash array. This makes lookup very fast.

Items with equal keys are allowed. When inserting two items with the same key, only the last inserted item will be accessible (last in, first out) until it is removed.

The TQDictIterator class can traverse the dictionary, but only in an arbitrary order. Multiple iterators may independently traverse the same dictionary.

When inserting an item into a dictionary, only the pointer is copied, not the item itself, i.e. a shallow copy is made. It is possible to make the dictionary copy all of the item's data (a deep copy) when an item is inserted. insert() calls the virtual function TQPtrCollection::newItem() for the item to be inserted. Inherit a dictionary and reimplement newItem() if you want deep copies.

When removing a dictionary item, the virtual function TQPtrCollection::deleteItem() is called. TQDict's default implementation is to delete the item if auto-deletion is enabled.

Example #1:

        TQDict<TQLineEdit> fields; // TQString keys, TQLineEdit* values
        fields.insert( "forename", new TQLineEdit( this ) );
        fields.insert( "surname", new TQLineEdit( this ) );

        fields["forename"]->setText( "Homer" );
        fields["surname"]->setText( "Simpson" );

        TQDictIterator<TQLineEdit> it( fields ); // See TQDictIterator
        for( ; it.current(); ++it )
            cout << it.currentKey() << ": " << it.current()->text() << endl;
        cout << endl;

        if ( fields["forename"] && fields["surname"] )
            cout << fields["forename"]->text() << " "
                << fields["surname"]->text() << endl;  // Prints "Homer Simpson"

        fields.remove( "forename" ); // Does not delete the line edit
        if ( ! fields["forename"] )
            cout << "forename is not in the dictionary" << endl;

In this example we use a dictionary to keep track of the line edits we're using. We insert each line edit into the dictionary with a unique name and then access the line edits via the dictionary.

Example #2:

        TQStringList styleList = TQStyleFactory::styles();
        styleList.sort();
        TQDict<int> letterDict( 17, false );
        for ( TQStringList::Iterator it = styleList.begin(); it != styleList.end(); ++it ) {
            TQString styleName = *it;
            TQString styleAccel = styleName;
            if ( letterDict[styleAccel.left(1)] ) {
                for ( uint i = 0; i < styleAccel.length(); i++ ) {
                    if ( ! letterDict[styleAccel.mid( i, 1 )] ) {
                        styleAccel = styleAccel.insert( i, '&' );
                        letterDict.insert(styleAccel.mid( i, 1 ), (const int *)1);
                        break;
                    }
                }
            } else {
                styleAccel = "&" + styleAccel;
                letterDict.insert(styleAccel.left(1), (const int *)1);
            }
            (void) new TQAction( styleName, TQIconSet(), styleAccel, parent );
        }

In the example we are using the dictionary to provide fast random access to the keys, and we don't care what the values are. The example is used to generate a menu of TQStyles, each with a unique accelerator key (or no accelerator if there are no unused letters left).

We first obtain the list of available styles, then sort them so that the menu items will be ordered alphabetically. Next we create a dictionary of int pointers. The keys in the dictionary are each one character long, representing letters that have been used for accelerators. We iterate through our list of style names. If the first letter of the style name is in the dictionary, i.e. has been used, we iterate over all the characters in the style name to see if we can find a letter that hasn't been used. If we find an unused letter we put the accelerator ampersand (&) in front of it and add that letter to the dictionary. If we can't find an unused letter the style will simply have no accelerator. If the first letter of the style name is not in the dictionary we use it for the accelerator and add it to the dictionary. Finally we create a TQAction for each style.

See also TQDictIterator, TQAsciiDict, TQIntDict, TQPtrDict, Collection Classes, and Non-GUI Classes.

## Member Function Documentation

### TQDict::TQDict ( int size = 17, bool caseSensitive = true )

Constructs a dictionary optimized for less than size entries.

We recommend setting size to a suitably large prime number (e.g. a prime that's slightly larger than the expected number of entries). This makes the hash distribution better which will lead to faster lookup.

If caseSensitive is true (the default), keys which differ only by case are considered different.

### TQDict::TQDict ( const TQDict<type> & dict )

Constructs a copy of dict.

Each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy).

### TQDict::~TQDict ()

Removes all items from the dictionary and destroys it. If setAutoDelete() is true, each value is deleted. All iterators that access this dictionary will be reset.

See also setAutoDelete().

### bool TQPtrCollection::autoDelete () const

Returns the setting of the auto-delete option. The default is false.

See also setAutoDelete().

### void TQDict::clear ()`[virtual]`

Removes all items from the dictionary.

The removed items are deleted if auto-deletion is enabled.

All dictionary iterators that operate on the dictionary are reset.

See also remove(), take(), and setAutoDelete().

Reimplemented from TQPtrCollection.

### uint TQDict::count () const`[virtual]`

Returns the number of items in the dictionary.

See also isEmpty().

Reimplemented from TQPtrCollection.

### type * TQDict::find ( const TQString & key ) const

Returns the item with key key, or 0 if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the most recently inserted item will be found.

Equivalent to the [] operator.

See also operator[]().

### void TQDict::insert ( const TQString & key, const type * item )

Inserts the key key with value item into the dictionary.

Multiple items can have the same key, in which case only the last item will be accessible using operator[]().

item may not be 0.

See also replace().

Example: themes/themes.cpp.

### bool TQDict::isEmpty () const

Returns true if the dictionary is empty, i.e. count() == 0; otherwise returns false.

See also count().

### TQDict<type> & TQDict::operator= ( const TQDict<type> & dict )

Assigns dict to this dictionary and returns a reference to this dictionary.

This dictionary is first cleared, then each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy), unless newItem() has been reimplemented.

### type * TQDict::operator[] ( const TQString & key ) const

Returns the item with key key, or 0 if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the most recently inserted item will be found.

Equivalent to the find() function.

See also find().

### TQDataStream & TQDict::read ( TQDataStream & s, TQPtrCollection::Item & item )`[virtual protected]`

Reads a dictionary item from the stream s and returns a reference to the stream.

The default implementation sets item to 0.

See also write().

### bool TQDict::remove ( const TQString & key )

Removes the item with key from the dictionary. Returns true if successful, i.e. if the item is in the dictionary; otherwise returns false.

If there are two or more items with equal keys, then the last item that was inserted will be removed.

The removed item is deleted if auto-deletion is enabled.

All dictionary iterators that refer to the removed item will be set to point to the next item in the dictionary's traversal order.

See also take(), clear(), and setAutoDelete().

### void TQDict::replace ( const TQString & key, const type * item )

Replaces the value of the key, key with item.

If the item does not already exist, it will be inserted.

item may not be 0.

Equivalent to:

            TQDict<char> dict;
                ...
            if ( dict.find( key ) )
                dict.remove( key );
            dict.insert( key, item );

If there are two or more items with equal keys, then the last item that was inserted will be replaced.

See also insert().

### void TQDict::resize ( uint newsize )

Changes the size of the hash table to newsize. The contents of the dictionary are preserved, but all iterators on the dictionary become invalid.

### void TQPtrCollection::setAutoDelete ( bool enable )

Sets the collection to auto-delete its contents if enable is true and to never delete them if enable is false.

If auto-deleting is turned on, all the items in a collection are deleted when the collection itself is deleted. This is convenient if the collection has the only pointer to the items.

The default setting is false, for safety. If you turn it on, be careful about copying the collection - you might find yourself with two collections deleting the same items.

Note that the auto-delete setting may also affect other functions in subclasses. For example, a subclass that has a remove() function will remove the item from its data structure, and if auto-delete is enabled, will also delete the item.

See also autoDelete().

Examples: grapher/grapher.cpp, scribble/scribble.cpp, and table/bigtable/main.cpp.

### uint TQDict::size () const

Returns the size of the internal hash array (as specified in the constructor).

See also count().

### void TQDict::statistics () const

Debugging-only function that prints out the dictionary distribution using tqDebug().

### type * TQDict::take ( const TQString & key )

Takes the item with key out of the dictionary without deleting it (even if auto-deletion is enabled).

If there are two or more items with equal keys, then the last item that was inserted will be taken.

Returns a pointer to the item taken out, or 0 if the key does not exist in the dictionary.

All dictionary iterators that refer to the taken item will be set to point to the next item in the dictionary traversal order.

See also remove(), clear(), and setAutoDelete().

### TQDataStream & TQDict::write ( TQDataStream & s, TQPtrCollection::Item ) const`[virtual protected]`

Writes a dictionary item to the stream s and returns a reference to the stream.

See also read().

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