vector - How can I split a vector into smaller vectors of size N?
问题描述
How to split a vector
let v: Vec<u8>; // vector with size x
into a vector of vectors of maxsize n? Pseudocode:
let n: usize = 1024;
let chunks_list: Vec<Vec<u8>> = chunks(v, n);
or using slices (to avoid copying):
let v: &[u8];
let chunks_list: Vec<&[u8]> = chunks(v, n);
解决方案
Rust slices already contain the necessary method for that: chunks.
Starting from this:
let src: Vec<u8> = vec![1, 2, 3, 4, 5];
you can get a vector of slices (no copy):
let dst: Vec<&[u8]> = src.chunks(3).collect();
or a vector of vectors (slower, heavier):
let dst: Vec<Vec<u8>> = src.chunks(3).map(|s| s.into()).collect();
推荐阅读
- c - 使用 vcpkg 为头文件安装库函数
- java - 如果我在方法中“抛出新的错误()”,在方法声明中追加和不追加“抛出错误”有什么区别?
- python - 根据python中的最近值合并2个数据框
- java - 在 Twilio 消息正文中包含的不是英文文本,它被替换为?
- python - 我需要从使用框架的网站上抓取数据
- ios - 如何更新已经呈现的上下文菜单中的值?
- php - 通过 Collection 访问 hasMany 关系函数
- jdbc - 使用 Jmeter JDBC 请求对 H2 数据库进行性能测试的问题
- r - Plotly scatterternary - 连续色彩美学的问题
- c++ - C++ 初始化/预初始化/fini 数组