问题描述
我想将一个大向量分成多个向量.我知道chunks()
,但是不确定从迭代器到2D Vec
的最佳方法.我发现以下方法可以工作,但是有没有更好的方法来编写此代码?
I want to chunk a large vector into a vector of vectors. I know about chunks()
, but am not sure of the best way to go from the iterator to a 2D Vec
. I have found the following to work, but is there a better way to write this?
let v: Vec<i32> = vec![1, 1, 1, 2, 2, 2, 3, 3, 3];
let v_chunked: Vec<Vec<i32>> = v.chunks(3).map(|x| x.to_vec()).collect();
println!("{:?}", v_chunked); // [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
类似于此操作的操作是分析后程序最慢的部分之一,我想知道如何对其进行改进.
An operation similar to this is one of the slowest parts of my program after profiling and I was wondering how to improve it.
推荐答案
如果Vec<Vec<i32>>
是您真正想要的,那么这是一种很好的方法.任何其他方法(不包括unsafe
代码,请参见下文)都不太可能显着提高速度或使用明显更少的内存.不管实际的代码如何,每个嵌套的Vec
都是一个新的内存分配,并且所有数据都需要复制-这实际上就是您的代码所做的全部操作.
If a Vec<Vec<i32>>
is what you really want then this is a pretty good way of doing it. Any other approach (excluding unsafe
code, see below) is unlikely to be significantly faster or use noticeably less memory. Regardless of the actual code, each nested Vec
is a new memory allocation and all the data will be need to copied - and that's essentially all that your code does.
表示这种2D结构的一种更为鲁棒"的方式是将Vec
切片成原始数据.这样一来,您就不会进行任何复制,也不会进行新的分配.
A more "Rusty" way to represent a 2D structure like this is a Vec
of slices into the original data. That way you don't do any copying and no new allocations.
let v_slices: Vec<&[i32]> = v.chunks(3).collect();
println!("{:?}", v_slices); // [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
这篇关于将大向量有效地分块为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!