How to idiomatically iterate one half of an array and modify the structure of the other?

后端 未结 1 2022
闹比i
闹比i 2020-12-12 01:40

What is the idiomatic way to iterate (read) over the first half of the vector and change the structure of the second half of the vector depending on the first? This is very

1条回答
  •  有刺的猬
    2020-12-12 02:18

    An idiomatic solution of this generic problem will be the same for Rust and C, as there's no constraints which would allow simplification.

    We need to use indexes because vector reallocation will invalidate the references contained by the iterators. We need to compare the index against the current length of the vector on each cycle because the length could be changed. Thus an idiomatic solution will look like this:

    let mut i = 0;
    while i < v.len() {
        let mut j = i + 1;
        while j < v.len() {
            if f(v[i], v[j]) {
                v.splice(j, 1);
            } else {
                j += 1;
            }
        }
        i += 1;
    }
    

    Playground link

    While this code covers the general case, it is rarely useful. It doesn't capture specifics, which are usually inherent to the problem at hand. In turn, the compiler is unable to catch any errors at compile time. I don't advise writing something like this without considering another approaches first.

    0 讨论(0)
提交回复
热议问题