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

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

问题描述

我想从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).

推荐答案

如果要删除元素,则可以使用

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天全站免登陆