简体   繁体   English

如何使用人造丝进行枚举迭代?

[英]How to iterate with enumeration using rayon?

I can iterate and process both index and the variable within such as:我可以迭代和处理索引和变量,例如:

let x = vec![5, 6, 7, 8];

for (index, val) in x.iter().enumerate() {
    println!("{} {}", val, index);
}

Now with rayon, from what I know, parallel iteration through par_iter() doesn't support enumerate because it has ParallelIterator .现在有了人造丝,据我所知,通过par_iter()的并行迭代不支持枚举,因为它有ParallelIterator

Rayon seem to have IndexedParallelIterator , but I am not sure how to use it to produce similar result as the simple for loop shown above. Rayon 似乎有IndexedParallelIterator ,但我不确定如何使用它来产生与上面显示的简单 for 循环类似的结果。

Is there anyway to keep track of the index of each value when parallel iterating?无论如何在并行迭代时跟踪每个值的索引? How would the simple for loop look like?简单的 for 循环会是什么样子?

When you create a ParallelIterator from a Vec by calling par_iter() it's also simultaneously an IndexedParallelIterator so you can call enumerate() on it to get the item indexes like so:当您通过调用par_iter()Vec创建ParallelIterator时,它同时也是一个IndexedParallelIterator ,因此您可以在其上调用enumerate()以获取项目索引,如下所示:

// rayon = "1.5"
use rayon::prelude::*;

fn main() {
    let x = vec![5, 6, 7, 8];
    x.par_iter().enumerate().for_each(|(index, val)| {
        println!("{} {}", val, index);
    });
}

playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM