How to create an iterator that yields elements of

2020-04-17 05:23发布

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]);
    }
}

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].

标签: rust iterator
1条回答
何必那么认真
2楼-- · 2020-04-17 06:17

One possibility:

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

as in:

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);
    }
}
查看更多
登录 后发表回答