将大向量有效地分块为向量 [英] Efficiently chunk large vector into a vector of vectors

查看:108
本文介绍了将大向量有效地分块为向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个大向量分成多个向量.我知道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]]

https://play. rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5031d4d0e43470242b8304d483967a25

类似于此操作的操作是分析后程序最慢的部分之一,我想知道如何对其进行改进.

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]]


:我确实有一个多余的地方,其中有一些代码,无需重新分配即可将Vec<i32>转换为Vec<Vec<i32>>.但是,已经指出它仍然具有未定义的行为,并且该问题基本上是无法解决的


I did have an extra bit here with some unsafe code that would transform a Vec<i32> into a Vec<Vec<i32>> without reallocating. However, it has been pointed out that it still has Undefined Behaviour, and that the problem is fundamentally not fixable

这篇关于将大向量有效地分块为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆