Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

rust - Efficiently mutate a vector while also iterating over the same vector

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 is that you can't have both a mutable and immutable borrow happening at the same time, but I'm not sure how to reframe my problem to get around this without cloning either the current element or the entire vector, which seems like a waste since I'm only ever mutating the current element, and it doesn't need to be compared to itself (I skip that case).

I'm sure there's an idiomatic way to do this in Rust.

struct MyStruct {
    a: i32,
}

fn main() {
    let mut v = vec![MyStruct { a: 1 }, MyStruct { a: 2 }, MyStruct { a: 3 }];

    for elem in v.iter_mut() {
        for other_elem in v.iter() {
            if other_elem.a > elem.a {
                elem.a += 1;
            }
        }
    }
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...