Rust: Vec> into Vec

后端 未结 2 1939
情话喂你
情话喂你 2021-01-18 22:58
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 Vec

相关标签:
2条回答
  • 2021-01-18 23:27

    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]);
    
    0 讨论(0)
  • 2021-01-18 23:29

    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.

    0 讨论(0)
提交回复
热议问题