Efficiently mutate a vector while also iterating over the same vector

后端 未结 2 1158
北海茫月
北海茫月 2020-11-27 08:13

I have a vector of structs, and I\'m comparing every element in the vector against every other element, and in certain cases mutating the current element.

My issue

2条回答
  •  [愿得一人]
    2020-11-27 08:52

    The simplest way is to just use indices, which don't involve any long-lived borrows:

    for i in 0..v.len() {
        for j in 0..v.len() {
            if i == j { continue; }
            if v[j].a > v[i].a {
                v[i].a += 1;
            }
        }
    }
    

    If you really, really want to use iterators, you can do it by dividing up the Vec into disjoint slices:

    fn process(elem: &mut MyStruct, other: &MyStruct) {
        if other.a > elem.a {
            elem.a += 1;
        }
    }
    
    for i in 0..v.len() {
        let (left, mid_right) = v.split_at_mut(i);
        let (mid, right) = mid_right.split_at_mut(1);
        let elem = &mut mid[0];
    
        for other in left {
            process(elem, other);
        }
        for other in right {
            process(elem, other);
        }
    }
    

提交回复
热议问题