如何创建一个迭代器,该迭代器生成由Rust中的索引列表指定的集合元素? [英] How to create an iterator that yields elements of a collection specified by a list of indices in Rust?

查看:136
本文介绍了如何创建一个迭代器,该迭代器生成由Rust中的索引列表指定的集合元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在使用给定索引列表遍历向量的简洁方法?我有类似的代码:

Is there a concise way to iterate over a vector using a given list of indices? I have code that looks similar to this:

fn main() {
    // Create a vector
    let v = vec![0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 7.8];

    // Create a series of indices
    let i = vec![3, 4, 2, 1];

    // Iterate over the elements in v in the order specified by each index in i
    for j in &i {
        println!("{}", v[*j]);
    }
}

我想对其进行修改,以便直接在v中的元素上循环,而不必在i中的索引上循环.基本上,它看起来类似于for x in vs[i].

I'd like to modify it so that I loop directly over elements in v rather than having to loop over the indices in i. Basically, something that looks similar to for x in vs[i].

推荐答案

一种可能性:

i.iter().map(|idx| v[*idx])

如:

fn main() {
    // Create a vector
    let v = vec![0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 7.8];

    // Create a series of indices
    let i = vec![3, 4, 2, 1];

    // Iterate over the elements in v in the order specified by i
    for j in i.iter().map(|idx| v[*idx]) {
        println!("{}", j);
    }
}

这篇关于如何创建一个迭代器,该迭代器生成由Rust中的索引列表指定的集合元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆