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

# <QtAlgorithms> - Generic Algorithms

The <QtAlgorithms> header file provides generic template-based algorithms. More...

### Functions

- RandomAccessIterator qBinaryFind ( RandomAccessIterator begin, RandomAccessIterator end, const T & value )
- void qBubbleSort ( BiIterator begin, BiIterator end )
- void qBubbleSort ( BiIterator begin, BiIterator end, LessThan lessThan )
- void qBubbleSort ( Container & c )
- OutputIterator qCopy ( InputIterator begin1, InputIterator end1, OutputIterator begin2 )
- BiIterator2 qCopyBackward ( BiIterator1 begin1, BiIterator1 end1, BiIterator2 end2 )
- void qCount ( InputIterator begin, InputIterator end, const T & value, Size & n )
- void qDeleteAll ( ForwardIterator begin, ForwardIterator end )
- void qDeleteAll ( const Container & c )
- bool qEqual ( InputIterator1 begin1, InputIterator1 end1, InputIterator2 begin2 )
- void qFill ( ForwardIterator begin, ForwardIterator end, const T & value )
- InputIterator qFind ( InputIterator begin, InputIterator end, const T & value )
- bool qGreater ( const T & t1, const T & t2 )
- void qHeapSort ( BiIterator begin, BiIterator end )
- void qHeapSort ( BiIterator begin, BiIterator end, LessThan lessThan )
- void qHeapSort ( Container & c )
- bool qLess ( const T & t1, const T & t2 )
- RandomAccessIterator qLowerBound ( RandomAccessIterator begin, RandomAccessIterator end, const T & value )
- void qSwap ( T & var1, T & var2 )
- RandomAccessIterator qUpperBound ( RandomAccessIterator begin, RandomAccessIterator end, const T & value )

## Detailed Description

The <QtAlgorithms> header file 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():

        QList<QString> 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" ]

The various algorithms have different requirements for the iterators they accept. For example, qFill() accepts two input iterators, the most minimal requirement for an iterator type. The requirements are specified for every algorithm. If an iterator of the wrong type is passed (for example, 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., `&amp`;) 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 Q_UINT16 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, QLinkedList, and QVector's non-const iterator types are random access iterators.

See also container classes.

## Function Documentation

### RandomAccessIterator qBinaryFind ( RandomAccessIterator begin, RandomAccessIterator end, const T & value )

Performs a binary search of the range [begin, end) and returns the position of an occurrence of value. If there are no occurrences of value, returns end.

The items in the range [begin, end) must be sorted in ascending order; see qHeapSort().

If there are many occurrences of the same value, any one of them could be returned. Use qLowerBound() or qUpperBound() if you need finer control.

Example:

        QVector<int> vect;
        vect << 3 << 3 << 6 << 6 << 6 << 8;

        QVector<int>::Iterator i =
                qBinaryFind(vect.begin(), vect.end(), 6);
        // i == vect.begin() + 2 (or 3 or 4)

This function requires the item type (in the example above, QString) to implement `operator<()`.

See the detailed description for an example usage.

See also qLowerBound(), qUpperBound(), and random access iterators.

### void qBubbleSort ( BiIterator begin, BiIterator end )

Sorts the items in range [begin, end) in ascending order using the bubble sort algorithm.

Example:

        QList<int> list;
        list << 33 << 12 << 68 << 6 << 12;
        qBubbleSort(list.begin(), list.end());
        // list: [ 6, 12, 12, 33, 68 ]

The bubble sort algorithm can be very slow on large data sets. Its behavior is said to be quadratic. Use this algorithm only if you are certain that there are only a very few items to sort, say, less than 30. If you can't guarantee that, use qHeapSort() instead.

This function requires the item type (in the example above, `int`) to implement `operator<()`.

See also qHeapSort() and bidirectional iterators.

### void qBubbleSort ( BiIterator begin, BiIterator end, LessThan lessThan )

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

Uses the lessThan function instead of `operator<()` to compare the items.

For example, here's how to sort the strings in a QList<QString> in case-insensitive alphabetical order:

        bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
        {
            return s1.toLower() < s2.toLower();
        }

        int doSomething()
        {
            QList<QString> list;
            list << "AlPha" << "beTA" << "gamma" << "DELTA";
            qBubbleSort(list.begin(), list.end(), caseInsensitiveLessThan);
            // list: [ "AlPha", "beTA", "DELTA", "gamma" ]
        }

To sort values in reverse order, pass qGreater<T> as the lessThan parameter. For example:

        QList<int> list;
        list << 33 << 12 << 68 << 6 << 12;
        qBubbleSort(list.begin(), list.end(), qGreater<int>);
        // list: [ 68, 33, 12, 12, 6 ]

See also qLess() and qGreater().

### void qBubbleSort ( Container & c )

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

This is the same as qBubbleSort(c.begin(), c.end());

### OutputIterator qCopy ( InputIterator begin1, InputIterator end1, OutputIterator begin2 )

Copies the items from range [begin1, end1) to range [begin2, ...), in the order in which they appear.

The item at position begin1 is assigned to that at position begin2; the item at position begin1 + 1 is assigned to that at position begin2 + 1; and so on.

Example:

        QList<QString> list;
        list << "one" << "two" << "three";

        QVector<QString> vect1(3);
        qCopy(list.begin(), list.end(), vect1.begin());
        // vect: [ "one", "two", "three" ]

        QVector<QString> vect2(8);
        qCopy(list.begin(), list.end(), vect2.begin() + 2);
        // vect: [ "", "", "one", "two", "three", "", "", "" ]

See also qCopyBackward(), input iterators, and output iterators.

### BiIterator2 qCopyBackward ( BiIterator1 begin1, BiIterator1 end1, BiIterator2 end2 )

Copies the items from range [begin1, end1) to range [..., end2).

The item at position end1 - 1 is assigned to that at position end2 - 1; the item at position end1 - 2 is assigned to that at position end2 - 2; and so on.

Example:

        QList<QString> list;
        list << "one" << "two" << "three";

        QVector<QString> vect(5);
        qCopyBackward(list.begin(), list.end(), vect.end());
        // vect: [ "", "", "one", "two", "three" ]

See also qCopy() and bidirectional iterators.

### void qCount ( InputIterator begin, InputIterator end, const T & value, Size & n )

Sets n to the number of occurrences of value in the range [begin, end).

Example:

        QList<int> list;
        list << 3 << 3 << 6 << 6 << 6 << 8;

        int countOf6;
        qCount(list.begin(), list.end(), countOf6, 6);
        // countOf6 == 3

        int countOf7;
        qCount(list.begin(), list.end(), countOf7, 7);
        // countOf7 == 0

This function requires the item type (in the example above, QString) to implement `operator==()`.

See also input iterators.

### void qDeleteAll ( ForwardIterator begin, ForwardIterator end )

Deletes all the items in the range [begin, end) using the C++ `delete` operator. The item type must be a pointer type (for example, `QWidget *`).

Example:

        QList<Employee *> list;
        list.append(new Employee("Blackpool", "Stephen"));
        list.append(new Employee("Twist", "Oliver"));

        qDeleteAll(list.begin(), list.end());
        list.clear();

Notice that qDeleteAll() doesn't remove the items from the container; it merely calls `delete` on them. In the example above, we call clear() on the container to remove the items.

See also forward iterators.

### void qDeleteAll ( const Container & c )

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

This is the same as qDeleteAll(c.begin(), c.end()).

### bool qEqual ( InputIterator1 begin1, InputIterator1 end1, InputIterator2 begin2 )

Compares the items in the range [begin1, end1) with the items in the range [begin2, ...). Returns true if all the items compare equal; otherwise returns false.

Example:

        QList<QString> list;
        list << "one" << "two << "three";

        QVector<QString> vect[3];
        vect[0] = "one";
        vect[1] = "two";
        vect[2] = "three";

        bool ret1 = qEqual(list.begin(), list.end(), vect.begin());
        // ret1 == true

        vect[2] = "seven";
        bool rec2 = qEqual(list.begin(), list.end(), vect.begin());
        // ret2 == false

This function requires the item type (in the example above, QString) to implement `operator==()`.

See also input iterators.

### void qFill ( ForwardIterator begin, ForwardIterator end, const T & value )

Fills the range [begin, end) with value.

Example:

        QList<QString> list;
        list << "one" << "two" << "three";

        qFill(list.begin(), list.end(), "eleven");
        // list: [ "eleven", "eleven", "eleven" ]

        qFill(list.begin() + 1, list.end(), "six");
        // list: [ "eleven", "six", "six" ]

See also qCopy() and forward iterators.

### InputIterator qFind ( InputIterator begin, InputIterator end, const T & value )

Returns an iterator to the first occurrence of value in a container in the range [begin, end). Returns end if value isn't found.

Example:

        QList<QString> list;
        list << "one" << "two" << "three";

        QList<QString>::Iterator i1 = qFind(list.begin(), list.end(),
                                            "two");
        // i1 == list.begin() + 1

        QList<QString>::Iterator i2 = qFind(list.begin(), list.end(),
                                            "seventy");
        // i2 == list.end()

This function requires the item type (in the example above, QString) to implement `operator==()`.

If the items in the range are in ascending order, you can get faster results by using qLowerBound() or qBinaryFind() instead of qFind().

See also qBinaryFind() and input iterators.

### bool qGreater ( const T & t1, const T & t2 )

Returns true if t1 > t2; otherwise returns false.

This function requires the item type to implement `operator>()`.

See also qLess() and qHeapSort().

### void qHeapSort ( BiIterator begin, BiIterator end )

Sorts the items in range [begin, end) in ascending order using the heap sort algorithm.

Example:

        QList<int> list;
        list << 33 << 12 << 68 << 6 << 12;
        qHeapSort(list.begin(), list.end());
        // list: [ 6, 12, 12, 33, 68 ]

The heap sort algorithm can be slower than bubble sort (qBubbleSort()) for very small data sets, but is much faster on large data sets. Its behavior is said to be linear-logarithmic, O(n log n).

This function requires the item type (in the example above, `int`) to implement `operator<()`.

See also qBubbleSort() and bidirectional iterators.

### void qHeapSort ( BiIterator begin, BiIterator end, LessThan lessThan )

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

Uses the lessThan function instead of `operator<()` to compare the items.

For example, here's how to sort the strings in a QList<QString> in case-insensitive alphabetical order:

        bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
        {
            return s1.toLower() < s2.toLower();
        }

        int doSomething()
        {
            QList<QString> list;
            list << "AlPha" << "beTA" << "gamma" << "DELTA";
            qHeapSort(list.begin(), list.end(), caseInsensitiveLessThan);
            // list: [ "AlPha", "beTA", "DELTA", "gamma" ]
        }

To sort values in reverse order, pass qGreater<T> as the lessThan parameter. For example:

        QList<int> list;
        list << 33 << 12 << 68 << 6 << 12;
        qHeapSort(list.begin(), list.end(), qGreater<int>);
        // list: [ 68, 33, 12, 12, 6 ]

Warning: Microsoft Visual C++ 6.0 has a bug that prevents the above code snippets from compiling. To work around this bug, assign the function pointer to a variable and pass that variable to qHeapSort(), like this:

        bool (*lessThan)(const QString &, const QString &) = qGreater<QString>;
        qHeapSort(vect.begin(), vect.end(), lessThan);

See also qLess() and qGreater().

### void qHeapSort ( Container & c )

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

This is the same as qHeapSort(c.begin(), c.end());

### bool qLess ( const T & t1, const T & t2 )

Returns true if t1 < t2; otherwise returns false.

This function requires the item type to implement `operator<()`.

See also qGreater() and qHeapSort().

### RandomAccessIterator qLowerBound ( RandomAccessIterator begin, RandomAccessIterator end, const T & value )

Performs a binary search of the range [begin, end) and returns the position of the first ocurrence of value. If no such item is found, returns the position where it should be inserted.

The items in the range [begin, end) must be sorted in ascending order; see qHeapSort().

Example:

        QList<int> list;
        list << 3 << 3 << 6 << 6 << 6 << 8;

        QList<int>::Iterator i = qLowerBound(list.begin(), list.end(), 5);
        list.insert(i, 5);
        // list: [ 3, 3, 5, 6, 6, 6, 8 ]

        i = qLowerBound(list.begin(), list.end(), 12);
        list.insert(i, 12);
        // list: [ 3, 3, 5, 6, 6, 6, 8, 12 ]

This function requires the item type (in the example above, `int`) to implement `operator<()`.

qLowerBound() can be used in conjunction with qUpperBound() to iterate over all occurrences of the same value:

        QVector<int> vect;
        vect << 3 << 3 << 6 << 6 << 6 << 8;
        QVector<int>::Iterator begin6 =
                qLowerBound(vect.begin(), vect.end(), 6);
        QVector<int>::Iterator end6 =
                qUpperBound(begin6, vect.end(), 6);

        QVector<int>::Iterator i = begin6;
        while (i != end6) {
            *i = 7;
            ++i;
        }
        // vect: [ 3, 3, 7, 7, 7, 8 ]

See also qUpperBound() and qBinaryFind().

### void qSwap ( T & var1, T & var2 )

Exchanges the values of variables var1 and var2.

Example:

        double pi = 3.14;
        double e = 2.71;

        qSwap(pi, e);
        // pi == 2.71, e == 3.14

### RandomAccessIterator qUpperBound ( RandomAccessIterator begin, RandomAccessIterator end, const T & value )

Performs a binary search of the range [begin, end) and returns the position of the one-past-the-last occurrence of value. If no such item is found, returns the position where the item should be inserted.

The items in the range [begin, end) must be sorted in ascending order; see qHeapSort().

Example:

        QList<int> list;
        list << 3 << 3 << 6 << 6 << 6 << 8;

        QList<int>::Iterator i = qUpperBound(list.begin(), list.end(), 5);
        list.insert(i, 5);
        // list: [ 3, 3, 5, 6, 6, 6, 8 ]

        i = qUpperBound(list.begin(), list.end(), 12);
        list.insert(i, 12);
        // list: [ 3, 3, 5, 6, 6, 6, 8, 12 ]

This function requires the item type (in the example above, `int`) to implement `operator<()`.

qUpperBound() can be used in conjunction with qLowerBound() to iterate over all occurrences of the same value:

        QVector<int> vect;
        vect << 3 << 3 << 6 << 6 << 6 << 8;
        QVector<int>::Iterator begin6 =
                qLowerBound(vect.begin(), vect.end(), 6);
        QVector<int>::Iterator end6 =
                qUpperBound(vect.begin(), vect.end(), 6);

        QVector<int>::Iterator i = begin6;
        while (i != end6) {
            *i = 7;
            ++i;
        }
        // vect: [ 3, 3, 7, 7, 7, 8 ]

See also qLowerBound() and qBinaryFind().