Home · Examples 


Generic Algorithms

The <QtAlgorithms> header provides generic template-based algorithms. Qt provides a number of global template functions in <QtAlgorithms> that work on containers and perform well-know algorithms. You can use these algorithms with any container class that provides STL-style iterators, including Qt's QList, QLinkedList, QVector, QMap, and QHash classes.

These functions have taken their inspiration from similar functions available in the STL <algorithm> header. Most of them have a direct STL equivalent; for example, qCopyBackward() is the same as STL's copy_backward() algorithm.

If STL is available on all your target platforms, you can use the STL algorithms instead of their Qt counterparts. One reason why you might want to use the the STL algorithms is that STL provides dozens and dozens of algorithms, whereas Qt only provides the most important ones, making no attempt to duplicate functionality that is already provided by the C++ standard.

Most algorithms take STL-style iterators as parameters. The algorithms are generic in the sense that they aren't bound to a specific iterator class; you can use them with any iterators that meet a certain set of requirements.

Let's take the qFill() algorithm as an example. Unlike QVector, QList has no fill() function that can be used to fill a list with a particular value. If you need that functionality, you can use qFill():

QStringList list;
list << "one" << "two" << "three";

qFill(list.begin(), list.end(), "eleven");
// list: [ "eleven", "eleven", "eleven" ]
qFill() takes a begin iterator, an end iterator, and a value. In the example above, we pass list.begin() and list.end() as the begin and end iterators, but this doesn't have to be the case:
qFill(list.begin() + 1, list.end(), "six");
// list: [ "eleven", "six", "six" ]
Different algorithms can have different requirements for the iterators they accept. For example, qFill() accepts two forward iterators. The iterator types required are specified for each algorithm. If an iterator of the wrong type is passed (for example, if QList::ConstIterator is passed as an output iterator), you will always get a compiler error, although not necessarily a very informative one.

Some algorithms have special requirements on the value type stored in the containers. For example, qEqual() requires that the value type supports operator==(), which it uses to compare items. Similarly, qDeleteAll() requires that the value type is a non-const pointer type (for example, QWidget *). The value type requirements are specified for each algorithm, and the compiler will produce an error if a requirement isn't met. The generic algorithms can be used on other container classes than those provided by Qt and STL. The syntax of STL-style iterators is modeled after C++ pointers, so it's possible to use plain arrays as containers and plain pointers as iterators. A common idiom is to use qBinaryFind() together with two static arrays: one that contains a list of keys, and another that contains a list of associated values. For example, the following code will look up an HTML entity (e.g., &;) in the name_table array and return the corresponding Unicode value from the value_table if the entity is recognized:

QChar resolveEntity(const QString &entity)
{
    static const QLatin1String name_table[] = {
        "AElig", "Aacute", ..., "zwnj"
    };
    static const ushort value_table[] = {
        0x0061, 0x00c1, ..., 0x200c
    };
    int N = sizeof(name_table) / sizeof(name_table[0]);

    const QLatin1String *name = qBinaryFind(name_table, name_table + N,
                                            entity);
    int index = name - name_table;
    if (index == N)
        return QChar();

    return QChar(value_table[index]);
}
This kind of code is for advanced users only; for most applications, a QMap- or QHash-based approach would work just as well:
QChar resolveEntity(const QString &entity)
{
    static QMap<QString, int> entityMap;

    if (!entityMap) {
        entityMap.insert("AElig", 0x0061);
        entityMap.insert("Aacute", 0x00c1);
        ...
        entityMap.insert("zwnj", 0x200c);
    }
    return QChar(entityMap.value(entity));
}

Types of Iterators

The algorithms have certain requirements on the iterator types they accept, and these are specified individually for each function. The compiler will produce an error if a requirement isn't met.

Input Iterators

An input iterator is an iterator that can be used for reading data sequentially from a container. It must provide the following operators: == and != for comparing two iterators, unary * for retrieving the value stored in the item, and prefix ++ for advancing to the next item.

The Qt containers' iterator types (const and non-const) are all input iterators.

Output Iterators

An output iterator is an iterator that can be used for writing data sequentially to a container or to some output stream. It must provide the following operators: unary * for writing a value (i.e., *it = val) and prefix ++ for advancing to the next item.

The Qt containers' non-const iterator types are all output iterators.

Forward Iterators

A forward iterator is an iterator that meets the requirements of both input iterators and output iterators.

The Qt containers' non-const iterator types are all forward iterators.

Bidirectional Iterators

A bidirectional iterator is an iterator that meets the requirements of forward iterators but that in addition supports prefix -- for iterating backward.

The Qt containers' non-const iterator types are all bidirectional iterators.

Random Access Iterators

The last category, random access iterators, is the most powerful type of iterator. It supports all the requirements of a bidirectional iterator, and supports the following operations:
i += n advances iterator i by n positions
i -= n moves iterator i back by n positions
i + n or n + i returns the iterator for the item n positions ahead of iterator i
i - n returns the iterator for the item n positions behind of iterator i
i - j returns the number of items between iterators i and j
i[n] same as *(i + n)
i < j returns true if iterator j comes after iterator i
QList and QVector's non-const iterator types are random access iterators.

See also:
container classes, and .


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Jambi 4.5.2_01