如何保留向量元素及其原始索引?

Tim*_*mmm 5 vector rust

如果我有一个,Vec我可以使用索引 via 迭代元素v.iter().enumerate(),并且我可以通过 删除元素v.retain()。有没有办法同时完成这两件事?

在这种情况下,索引不能再用于访问元素 - 它将是循环开始之前元素的索引。

我可以自己实现这个,但要像.retain()我需要使用的那样高效unsafe,这是我想避免的。

这就是我想要的结果:

let mut v: Vec<i32> = vec![1, 2, 3, 4, 5, 4, 7, 8];

v.iter()
    .retain_with_index(|(index, item)| (index % 2 == 0) || item == 4);

assert(v == vec![1, 3, 4, 5, 4, 7]);
Run Code Online (Sandbox Code Playgroud)

ric*_*gle 6

@Timmmm@Hauleth的答案非常务实,我想提供几个替代方案。

这是一个包含一些基准测试和测试的游乐场: https://play.rust-lang.org/? version=nightly&mode=debug&edition=2018&gist=cffc3c39c4b33d981a1a034f3a092e7b

这很丑陋,但如果你真的想要一个方法,你可以使用一个新特征v.retain_with_index()对该方法进行一些复制粘贴:retain

trait IndexedRetain<T> {
    fn retain_with_index<F>(&mut self, f: F)
    where
        F: FnMut(usize, &T) -> bool;
}

impl<T> IndexedRetain<T> for Vec<T> {
    fn retain_with_index<F>(&mut self, mut f: F)
    where
        F: FnMut(usize, &T) -> bool, // the signature of the callback changes
    {
        let len = self.len();
        let mut del = 0;
        {
            let v = &mut **self;

            for i in 0..len {
                // only implementation change here
                if !f(i, &v[i]) {
                    del += 1;
                } else if del > 0 {
                    v.swap(i - del, i);
                }
            }
        }
        if del > 0 {
            self.truncate(len - del);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该示例如下所示:

v.retain_with_index(|index, item| (index % 2 == 0) || item == 4);
Run Code Online (Sandbox Code Playgroud)

或者......更好的是,您可以使用高阶函数:

fn with_index<T, F>(mut f: F) -> impl FnMut(&T) -> bool
where
    F: FnMut(usize, &T) -> bool,
{
    let mut i = 0;
    move |item| (f(i, item), i += 1).0
}
Run Code Online (Sandbox Code Playgroud)

这样这个例子现在看起来像这样:

v.retain(with_index(|index, item| (index % 2 == 0) || item == 4));
Run Code Online (Sandbox Code Playgroud)

(我的偏好是后者)