IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

<QtAlgorithms> - Generic Algorithms

The <QtAlgorithms> header includes the generic, template-based algorithms.

Article lu   fois.

L'auteur

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

<QtAlgorithms> - Generic Algorithms

  • Header: QtAlgorithms

  • Group: <QtAlgorithms> is part of funclists

Detailed Description

Qt provides a number of global template functions in <QtAlgorithms> that work on containers and perform small tasks to make life easier, such as qDeleteAll(), which invokes operator delete on all items in a given container or in a given range. You can use these algorithms with any container class that provides STL-style iterators, including Qt's QList, QLinkedList, QVector, QMap, and QHash classes.

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.

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, 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:

 
Sélectionnez
QChar resolveEntity(const QString &amp;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:

 
Sélectionnez
QChar resolveEntity(const QString &amp;entity)
{
    static QMap&lt;QString, int&gt; 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.

Qt and the STL Algorithms

Historically, Qt used to provide functions which were direct equivalents of many STL algorithmic functions. Starting with Qt 5.0, you are instead encouraged to use directly the implementations available in the STL; most of the Qt ones have been deprecated (although they are still available to keep the old code compiling).

Porting guidelines

Most of the time, an application using the deprecated Qt algorithmic functions can be easily ported to use the equivalent STL functions. You need to:

  1. add the #include <algorithm> preprocessor directive;

  2. replace the Qt functions with the STL counterparts, according to the table below.

Qt function

STL function

qBinaryFind

std::binary_search or std::lower_bound

qCopy

std::copy

qCopyBackward

std::copy_backward

qEqual

std::equal

qFill

std::fill

qFind

std::find

qCount

std::count

qSort

std::sort

qStableSort

std::stable_sort

qLowerBound

std::lower_bound

qUpperBound

std::upper_bound

qLess

std::less

qGreater

std::greater

The only cases in which the port may not be straightforward is if the old code relied on template specializations of the qLess() and/or the qSwap() functions, which were used internally by the implementations of the Qt algorithmic functions, but are instead ignored by the STL ones.

In case the old code relied on the specialization of the qLess() functor, then a workaround is explicitly passing an instance of the qLess() class to the STL function, for instance like this:

 
Sélectionnez
std::sort(container.begin(), container.end(), qLess&lt;T&gt;());

Instead, since it's not possible to pass a custom swapper functor to STL functions, the only workaround for a template specialization for qSwap() is providing the same specialization for std::swap().

See Also

Function Documentation

 

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:

 
Sélectionnez
QList&lt;Employee *&gt; 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.

This function can also be used to delete items stored in associative containers, such as QMap and QHash. Only the objects stored in each container will be deleted by this function; objects used as keys will not be deleted.

See Also

void qDeleteAll(const Container &c)

This is an overloaded function.

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

Obsolete Members for <QtAlgorithms>

The following members of class <QtAlgorithms> are deprecated. We strongly advise against using them in new code.

Obsolete Function Documentation

 
int qGreater()

This function is deprecated. We strongly advise against using it in new code.

Use std::greater instead.

Returns a functional object, or functor, that can be passed to qSort() or qStableSort().

Example:

 
Sélectionnez
QList&lt;int&gt; list;
list &lt;&lt; 33 &lt;&lt; 12 &lt;&lt; 68 &lt;&lt; 6 &lt;&lt; 12;
qSort(list.begin(), list.end(), qGreater&lt;int&gt;());
// list: [ 68, 33, 12, 12, 6 ]
See Also

See also qLess<T>()

int qLess()

This function is deprecated. We strongly advise against using it in new code.

Use std::less instead.

Returns a functional object, or functor, that can be passed to qSort() or qStableSort().

Example:

 
Sélectionnez
QList&lt;int&gt; list;
list &lt;&lt; 33 &lt;&lt; 12 &lt;&lt; 68 &lt;&lt; 6 &lt;&lt; 12;
qSort(list.begin(), list.end(), qLess&lt;int&gt;());
// list: [ 6, 12, 12, 33, 68 ]
See Also

See also qGreater<T>()

void qSwap(T &var1, T &var2)

This function is deprecated. We strongly advise against using it in new code.

Use std::swap instead.

Exchanges the values of variables var1 and var2.

Example:

 
Sélectionnez
double pi = 3.14;
double e = 2.71;

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

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+