Rust: Vec<Vec<T>> into Vec<T>

你离开我真会死。 提交于 2021-01-20 04:28:32

问题


let a = vec![ vec![1, 2], vec![3, 4], vec![5, 6] ];

How can I gather into a single Vec all the values contained in all the Vecs in a ?


回答1:


You can use the flatten operator to remove the nesting of the vectors.

The following example is taken from the link.

let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);



回答2:


Steve's answer is correct, but you should also know about flat_map -- there's a good chance that that's what you really want to use, that it would make your code simpler and faster. You probably don't need to ever create a Vec of Vecs -- just an Iterator of Iterators that you flat_map and then collect.



来源:https://stackoverflow.com/questions/61287299/rust-vecvect-into-vect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!