是否可以就地过滤向量? [英] is it possible to filter on a vector in-place?

查看:15
本文介绍了是否可以就地过滤向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Vec 中删除一些元素,但是 vec.iter().filter().collect() 使用借用的项目创建了一个新向量.

I'd like to remove some elements from a Vec, but vec.iter().filter().collect() creates a new vector with borrowed items.

我想在不分配额外内存的情况下改变原始 Vec(并保留已移除元素的内存作为向量的额外容量).

I'd like to mutate the original Vec without extra memory allocation (and keep memory of removed elements as an extra capacity of the vector).

推荐答案

如果要删除元素,可以使用retain(),如果闭包返回 false,则从向量中移除元素:

If you want to remove elements, you can use retain(), which removes elements from the vector if the closure returns false:

let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);

如果你想就地修改元素,你必须在 for x in vec.iter_mut() 中进行.

If you want to modify the elements in place, you have to do that in a for x in vec.iter_mut().

这篇关于是否可以就地过滤向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆