我有一个QList
并且想要并行处理它的所有元素。问题是我需要将参数传递给 my_function
。下面的代码不允许这样做。
QList<something> output = QtConcurrent::blockingMapped(
input,
my_function
);
我可以为每组参数使用不同的函数。我也可以使用全局变量。我也可能会尝试重写 QT 函数中的构建。不过,应该有更好的解决方案。有什么想法吗?
最佳答案
假设您要传递给函数的参数与项无关,您可以创建一个扩展 std::unary_function<const something&,void>
的仿函数。它的构造函数接受您想要传递给它的参数。然后,在要使用该函数的地方使用仿函数。例如,
struct MyFunctor : public std::unary_function<const something&,void> {
public:
myFunctor(int s) { _i = i; }
void operator()(something& str) {
something.apply(_i);
}
private:
int _i;
};
…
MyFunctor myFunctor(i);
QList<something> output = QtConcurrent::blockingMapped(
input,
myFunctor
);
关于c++ - QT,并发编程和向函数传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6402123/