我有一个整数的 Vec ,我想创建一个新的 Vec ,其中包含那些整数和这些整数的平方.我可以必须这样做:
I have a Vec of integers and I want to create a new Vec which contains those integers and squares of those integers. I could do this imperatively:
let v = vec![1, 2, 3]; let mut new_v = Vec::new(); // new instead of with_capacity for simplicity sake. for &x in v.iter() { new_v.push(x); new_v.push(x * x); } println!("{:?}", new_v);但是我想使用迭代器.我想出了这段代码:
but I want to use iterators. I came up with this code:
let v = vec![1, 2, 3]; let new_v: Vec<_> = v.iter() .flat_map(|&x| vec![x, x * x]) .collect(); println!("{:?}", new_v);,但它在 flat_map 函数中分配了一个中间 Vec .
but it allocates an intermediate Vec in the flat_map function.
如何在没有分配的情况下使用 flat_map ?
How to use flat_map without allocations?
推荐答案您可以使用为此, ArrayVec .
You can use an ArrayVec for this.
let v = vec![1, 2, 3]; let new_v: Vec<_> = v.iter() .flat_map(|&x| ArrayVec::from([x, x * x])) .collect();使数组成为按值迭代器,这样就无需讨论 ArrayVec ,请参见 github/rust-lang/rust/issues/25725 和链接的PR.
Making arrays be by-value iterators, so that you wouldn't need ArrayVec has been discussed, see github/rust-lang/rust/issues/25725 and the linked PRs.
更多推荐
如何避免在Iterator :: flat
发布评论