本文介绍了如何避免在Iterator :: flat_map中进行分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数的 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 ,请参见 https://github.com/rust-lang/rust/issues/25725 和链接的PR.

Making arrays be by-value iterators, so that you wouldn't need ArrayVec has been discussed, see https://github.com/rust-lang/rust/issues/25725 and the linked PRs.

这篇关于如何避免在Iterator :: flat_map中进行分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:04