QtConcurrent::mapped等方法如何传递当前处理元素的索引?
QtConcurrent带索引处理的优雅解决方案
嘿,这个问题我太熟悉了!你完全不用手动创建std::pair<int, T>这种冗余结构——QtConcurrent本身就提供了带索引的系列方法,完美匹配你的需求!
核心思路:使用带Indexed后缀的方法
Qt为mapped/filter/map/filtered这些方法都提供了对应的索引版,命名就是在原方法名后加Indexed。这些方法的处理函数会自动把元素的索引和元素本身作为参数传递给你,完全不需要额外存储索引。
具体用法示例
假设你有一个QVector<T>类型的集合someVector,需要根据元素的索引做处理,下面是几种常见场景的代码:
1. 用mappedIndexed替代mapped(生成新集合)
如果你需要返回处理后的新集合,就用mappedIndexed,处理函数接收int index和const T& element两个参数:
#include <QtConcurrent> #include <QVector> // 自定义处理函数,带索引参数 T handleElement(int index, const T& element) { // 这里写你的索引相关逻辑,比如根据奇偶索引做不同处理 if (index % 2 == 0) { return element * 1.5; // 示例:偶数索引元素放大1.5倍 } else { return element * 0.8; // 奇数索引元素缩小到0.8倍 } } int main() { QVector<double> someVector = {1.0, 2.0, 3.0, 4.0, 5.0}; // 使用mappedIndexed替代mapped QFuture<double> future = QtConcurrent::mappedIndexed(someVector, handleElement); QVector<double> result = future.result(); // 获取处理后的结果 }
如果不想单独写函数,用lambda表达式更简洁:
QFuture<double> future = QtConcurrent::mappedIndexed(someVector, [](int index, const double& elem) { return index % 2 == 0 ? elem * 1.5 : elem * 0.8; });
2. 其他索引版方法对应
mapIndexed:对应map,原地修改元素,处理函数接收int index和T& element(可修改引用):QtConcurrent::mapIndexed(someVector, [](int index, double& elem) { elem = index % 2 == 0 ? elem * 1.5 : elem * 0.8; });filterIndexed:对应filter,过滤元素,处理函数返回bool决定是否保留该元素:QtConcurrent::filterIndexed(someVector, [](int index, const double& elem) { return index % 2 == 0; // 只保留偶数索引的元素 });filteredIndexed:对应filtered,返回过滤后的新集合:QFuture<double> future = QtConcurrent::filteredIndexed(someVector, [](int index, const double& elem) { return index % 2 == 0; }); QVector<double> filteredResult = future.result();
为什么这个方案更好?
相比你手动创建QVector<std::pair<int, T>>的方式:
- 不需要额外存储索引,节省内存空间;
- 代码更简洁直观,完全遵循Qt的API设计风格;
- 原生支持并发处理的优化,性能更有保障。
内容的提问来源于stack exchange,提问作者schlenger
相关产品推荐
相关产品推荐

