Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

<QtConcurrentFilter> - Concurrent Filter and Filter-Reduce

The <QtConcurrentFilter> header provides concurrent Filter and Filter-Reduce. More...

Functions

QFuture<void> filter ( Sequence & sequence, FilterFunction filterFunction )
QFuture<T> filtered ( const Sequence & sequence, FilterFunction filterFunction )
QFuture<T> filtered ( ConstIterator begin, ConstIterator end, FilterFunction filterFunction )
QFuture<T> filteredReduced ( const Sequence & sequence, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce )
QFuture<T> filteredReduced ( ConstIterator begin, ConstIterator end, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce )

These functions are a part of the Qt Concurrent framework.

The QtConcurrent::filter(), QtConcurrent::filtered() and QtConcurrent::filteredReduced() functions filter items in a sequence such as a QList or a QVector in parallel. QtConcurrent::filter() modifies a sequence in-place, QtConcurrent::filtered() returns a new sequence containing the filtered content, and QtConcurrent::filteredReduced() returns a single result.

Each of the above functions have a blocking variant that returns the final result instead of a QFuture. You use them in the same way as the asynchronous variants.

 QStringList strings = ...;

 // each call blocks until the entire operation is finished
 QStringList lowerCaseStrings = QtConcurrent::blockingFiltered(strings, allLowerCase);

 QtConcurrent::blockingFilter(strings, allLowerCase);

 QSet<QString> dictionary = QtConcurrent::blockingFilteredReduced(strings, allLowerCase, addToDictionary);

Note that the result types above are not QFuture objects, but real result types (in this case, QStringList and QSet<QString>).

Concurrent Filter

QtConcurrent::filtered() takes an input sequence and a filter function. This filter function is then called for each item in the sequence, and a new sequence containing the filtered values is returned.

The filter function must be of the form:

 bool function(const T &t);

T must match the type stored in the sequence. The function returns true if the item should be kept, false if it should be discarded.

This example shows how to keep strings that are all lower-case from a QStringList:

 bool allLowerCase(const QString &string)
 {
     return string.lowered() == string;
 }

 QStringList strings = ...;
 QFuture<QString> lowerCaseStrings = QtConcurrent::filtered(strings, allLowerCase);

The results of the filter are made available through QFuture. See the QFuture and QFutureWatcher documentation for more information on how to use QFuture in your applications.

If you want to modify a sequence in-place, use QtConcurrent::filter():

 QStringList strings = ...;
 QFuture<void> future = QtConcurrent::filter(strings, allLowerCase);

Since the sequence is modified in place, QtConcurrent::filter() does not return any results via QFuture. However, you can still use QFuture and QFutureWatcher to monitor the status of the filter.

Concurrent Filter-Reduce

QtConcurrent::filteredReduced() is similar to QtConcurrent::filtered(), but instead of returing a sequence with the filtered results, the results are combined into a single value using a reduce function.

The reduce function must be of the form:

 V function(T &result, const U &intermediate)

T is the type of the final result, U is the type of items being filtered. Note that the return value and return type of the reduce function are not used.

Call QtConcurrent::filteredReduced() like this:

 void addToDictionary(QSet<QString> &dictionary, const QString &string)
 {
     dictionary.insert(string);
 }

 QStringList strings = ...;
 QFuture<QSet<QString> > dictionary = QtConcurrent::filteredReduced(strings, allLowerCase, addToDictionary);

The reduce function will be called once for each result kept by the filter function, and should merge the intermediate into the result variable. QtConcurrent::filteredReduced() guarantees that only one thread will call reduce at a time, so using a mutex to lock the result variable is not neccesary. The QtConcurrent::ReduceOptions enum provides a way to control the order in which the reduction is done.

Additional API Features

Using Iterators instead of Sequence

Each of the above functions has a variant that takes an iterator range instead of a sequence. You use them in the same way as the sequence variants:

 QStringList strings = ...;
 QFuture<QString> lowerCaseStrings = QtConcurrent::filtered(strings.constBegin(), strings.constEnd(), allLowerCase);

 // filter in-place only works on non-const iterators
 QFuture<void> future = QtConcurrent::filter(strings.begin(), strings.end(), allLowerCase);

 QFuture<QSet<QString> > dictionary = QtConcurrent::filteredReduced(strings.constBegin(), strings.constEnd(), allLowerCase, addToDictionary);

Using Member Functions

QtConcurrent::filter(), QtConcurrent::filtered(), and QtConcurrent::filteredReduced() accept pointers to member functions. The member function class type must match the type stored in the sequence:

 // keep only images with an alpha channel
 QList<QImage> images = ...;
 QFuture<void> alphaImages = QtConcurrent::filter(strings, &QImage::hasAlphaChannel);

 // keep only gray scale images
 QList<QImage> images = ...;
 QFuture<QImage> grayscaleImages = QtConcurrent::filtered(images, &QImage::isGrayscale);

 // create a set of all printable characters
 QList<QChar> characters = ...;
 QFuture<QSet<QChar> > set = QtConcurrent::filteredReduced(characters, &QChar::isPrint, &QSet<QChar>::insert);

Note that when using QtConcurrent::filteredReduced(), you can mix the use of normal and member functions freely:

 // can mix normal functions and member functions with QtConcurrent::filteredReduced()

 // create a dictionary of all lower cased strings
 extern bool allLowerCase(const QString &string);
 QStringList strings = ...;
 QFuture<QSet<int> > averageWordLength = QtConcurrent::filteredReduced(strings, allLowerCase, QSet<QString>::insert);

 // create a collage of all gray scale images
 extern void addToCollage(QImage &collage, const QImage &grayscaleImage);
 QList<QImage> images = ...;
 QFuture<QImage> collage = QtConcurrent::filteredReduced(images, &QImage::isGrayscale, addToCollage);

Using Function Objects

QtConcurrent::filter(), QtConcurrent::filtered(), and QtConcurrent::filteredReduced() accept function objects, which can be used to add state to a function call. The result_type typedef must define the result type of the function call operator:

 struct StartsWith
 {
     StartsWith(const QString &string)
     : m_string(string) { }

     typedef bool result_type;

     bool operator()(const QString &testString)
     {
         return testString.startsWith(m_string);
     }

     QString m_string;
 };

 QList<QString> strings = ...;
 QFuture<QString> fooString = QtConcurrent::filtered(images, StartsWith(QLatin1String("Foo")));

Using Bound Function Arguments

Note that Qt does not provide support for bound functions. This is provided by 3rd party libraries like Boost or C++ TR1 Library Extensions.

If you want to use a filter function takes more than one argument, you can use boost::bind() or std::tr1::bind() to transform it onto a function that takes one argument.

As an example, we use QString::contains():

 bool QString::contains(const QRegExp &regexp) const;

QString::contains() takes 2 arguments (including the "this" pointer) and can't be used with QtConcurrent::filtered() directly, because QtConcurrent::filtered() expects a function that takes one argument. To use QString::contains() with QtConcurrent::filtered() we have to provide a value for the regexp argument:

 boost::bind(&QString::contains, QRegExp("^\\S+$")); // matches strings without whitespace

The return value from boost::bind() is a function object (functor) with the following signature:

 bool contains(const QString &string)

This matches what QtConcurrent::filtered() expects, and the complete example becomes:

 QStringList strings = ...;
 boost::bind(static_cast<bool(QString::*)(const QRegExp&)>( &QString::contains ), QRegExp("..." ));

Function Documentation

QFuture<void> QtConcurrent::filter ( Sequence & sequence, FilterFunction filterFunction )

Calls filterFunction once for each item in sequence. If filterFunction returns true, the item is kept in sequence; otherwise, the item is removed from sequence.

QFuture<T> QtConcurrent::filtered ( const Sequence & sequence, FilterFunction filterFunction )

Calls filterFunction once for each item in sequence and returns a new Sequence of kept items. If filterFunction returns true, a copy of the item is put in the new Sequence. Otherwise, the item will not appear in the new Sequence.

QFuture<T> QtConcurrent::filtered ( ConstIterator begin, ConstIterator end, FilterFunction filterFunction )

Calls filterFunction once for each item from begin to end and returns a new Sequence of kept items. If filterFunction returns true, a copy of the item is put in the new Sequence. Otherwise, the item will not appear in the new Sequence.

QFuture<T> QtConcurrent::filteredReduced ( const Sequence & sequence, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce )

Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true.

Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence.

QFuture<T> QtConcurrent::filteredReduced ( ConstIterator begin, ConstIterator end, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce )

Calls filterFunction once for each item from begin to end. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true.

Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, the reduceFunction is called in the order of the original sequence.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 85
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 20
  5. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
Page suivante

Le Qt Developer Network au hasard

Logo

QSqlTableModel en action

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.6
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web