如何避免在Iterator :: flat

编程入门 行业动态 更新时间:2024-10-26 02:29:53
本文介绍了如何避免在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 ,请参见 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

本文发布于:2023-10-28 05:17:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535637.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Iterator   flat

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!