首页 > 解决方案 > C++ Qt QtConcurrent::filteredReduced from QVector of std::shared_ptr

问题描述

我有一个vectorof shared_ptrsmy class Person,看起来像:

QVector <std::shared_ptr<const Person>> vecOfPeople;

Person 的领域之一是age,我想用QtConcurrent::filteredReduced例如有多少人来计算50,我发现很难理解如何去做。我有一个bool返回函数isOver50

bool isOver50(std::shared_ptr<const Person> &person)
{
    return person->getAge() > 50;
}

如果我理解得很好,应该还有一个reduction函数,在我的代码中看起来像:

void reduction(int &result, std::shared_ptr<const Person> &person)
{
    result++;
}

最后,代码filteredReduced如下:

QFuture<int> futureOver50 = QtConcurrent::filteredReduced(vecOfPeople, isOver50, reduction);

futureOver50.waitForFinished();

qDebug() << futureOver50.result();

这不能编译,我敢打赌,reduction功能有问题,但我不知道它是什么。

标签: c++qtqtconcurrent

解决方案


Qt 文档

过滤器函数必须采用以下形式:

bool function(const T &t);

reduce 函数必须采用以下形式:

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

您的shared_ptr参数是非常量引用(即使指向的类型是常量),Qt 想要传递常量引用,从而导致编译错误。

相反,请考虑使用

bool isOver50(const std::shared_ptr<const Person> &person);
void reduction(int &result, const std::shared_ptr<const Person> &person);

将来,请尝试将实际的错误消息与您的问题一起提交,这样可以更快地诊断这些问题


推荐阅读