How to create an iterator that yields elements of a collection specified by a list of indices in Rust?

后端 未结 1 1485
滥情空心
滥情空心 2021-01-22 17:46

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

f         


        
相关标签:
1条回答
  • 2021-01-22 18:23

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题