#includeQFuture calcDotProduct(const QVector & v1, const QVector & v2) { return QtConcurrent::mappedReduced(v1, v2, std::multiplies (), std::plus ()); } void runDotProduct() { QVector v1{ 1.0, 2.0, 3.0, 4.0, 5.0 }; QVector v2{ 2.0, 4.0, 6.0, 8.0, 10.0 }; QFuture future = calcDotProduct(v1, v2); QFutureWatcher watcher; watcher.setFuture(future); QObject::connect(&watcher, &QFutureWatcher ::finished, [=]() { double result = future.result(); qDebug() << "Dot Product: " << result; }); }
#includeIn this example, we use QFuture to calculate the first N terms of the Fibonacci sequence. We first construct a list of indices and then use QFuture to map that list to the values of the sequence using the fib function. We then loop through the results and print them to the console. The package library for QFuture is Qt.int fib(int n) { if (n <= 2) { return 1; } return fib(n - 1) + fib(n - 2); } void printFibs(int numberToPrint) { QList indices; for (int i = 1; i <= numberToPrint; i++) { indices << i; } QFuture future = QtConcurrent::mapped(indices, fib); QStringList results; for (int i = 0; i < numberToPrint; i++) { results << QString::number(future.resultAt(i)); } qDebug() << results.join(", "); }