How to idiomatically iterate one half of an array

2019-01-20 15:17发布

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 abstract but some algorithms could be boiled down to this problem. I want to write this simplified C++ example in Rust:

for (var i = 0; i < vec.length; i++) {
    for (var j = i + 1 ; j < vec.length; j++) {
        if (f(vec[i], vec[j])) {
            vec.splice(j, 1);
            j--;
        }
    }
}

1条回答
做自己的国王
2楼-- · 2019-01-20 15:48

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.

查看更多
登录 后发表回答