Is there a way to do double looping with Rust only with Iterator?

Asked 1 years ago, Updated 1 years ago, 103 views

If you want to loop a one-dimensional array into a triangle and process all the combinations, I think Java will be as follows.

Foo[]data=...;
for(inti=0;i<data.length();i++){
    for(int j=i+1;j<data.length();j++){
        // Calculated using various data[i] and data[j]
        data[i].bar+=...;
        data[j].bar+=...;
    }
}

Is there a way to do this with Rust and Iterator only?
I thought it would be better if I could make a copy so that I wouldn't change the original iter in the internal loop (see the original data instead of copying), but I couldn't find such a function.

let mut data:Vec<Foo>=...;
let mutter=data.iter_mut();
whilelet Some(idata)=iter.next(){
     // I want to avoid consuming `iter` for external loops in internal loops
    let mut inner_iter=iter.clone();
    for jdata in inner_iter{
        // Calculated using various idata and jdata
        idata.bar+=...;
        jdata.bar+=...;
    }
}

rust

2022-09-30 19:56

2 Answers

let muta:Vec<i32>=(0..10).collect();
for in 1..a.len() {
    let(af,ae) = a.split_at_mut(i);
    for vinae.iter_mut(){
        af[i-1]+=*v;
        *v+=1
    }
}

You can use split_at_mut to view one mutable array in two mutable arrays.I'm using index for the first for, so I can't say it's just the iterator, but w


2022-09-30 19:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.