Aleph0
Aleph0

Reputation: 6084

Generic Search Algorithms for Qt container classes

The STL overs a variety of functions to find elements in container classes. Are there similar functions in for Qt 5.5 container classes e.g. QList or QVector?

Especially, I'm looking for an equivalent one-liner i.e. std::find_if using Qt containers and Qt algorithms:

int main(int arg, char** args) {
    std::vector<int> c = { 2,3,4,6,6,15 };
    if (std::find_if(c.begin(), c.end(), [](const int& value) { return value % 5 == 0; }) != c.end()) {
        std::cout << "At least one element divisible by 5." << std::endl;
    } else {
        std::cout << "No element is divisible by 5." << std::endl;
    }
    return 0;
}

The predicate of an element being divisible by 5 should be just serve as an example.

Does the Qt Framework provides such nice algorithms?

Upvotes: 5

Views: 3432

Answers (2)

The standard C++ algorithms are meant to work with any container that fulfills the requirements of a given algorithm. The relevant standard containers are not special here: they happen to fulfill the requirements. Just as Qt containers do, and plenty of other containers. You'd be expected to write your own containers or iterator adapters in the course of your work anyway, specifically to leverage the standard algorithms.

For example, you can have an iterator adapter for QGraphicsScene or QLayout, or have to create an iterator for circular data structures.

Upvotes: 1

talamaki
talamaki

Reputation: 5472

STL algorithms defined in algorithm header can be used with Qt containers. If Qt lacks an equivalent algorithm there is no reason to avoid using the STL algorithm. If Qt is built with STL support it should work by default.

#include <algorithm> // std::find_if
#include <QApplication>
#include <QVector>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QVector<int> c{ 2,3,4,6,6,15 };
    if (std::find_if(c.begin(), c.end(), [](const int& value) { return value % 5 == 0; }) != c.end()) {
        ...
    }
    return app.exec();
}

Upvotes: 7

Related Questions