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

牧云@^-^@ 提交于 2019-11-28 14:09:55
red75prime

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!