daniellga
daniellga

Reputation: 1224

How can I concatenate many Vec<Vec<f64>> to produce another Vec<Vec<f64>>?

Is there an easy and optimal way to combine a and b to get c? I am struggling with this since I can't use index for c because it's not initialized. I am trying to avoid initializing c using 2 vectors of zeroes.

let mut a: Vec<Vec<f64>> = Vec::with_capacity(2);

a.push(vec![1., 2., 3.]);
a.push(vec![4., 5., 6.]);

let mut b: Vec<Vec<f64>> = Vec::with_capacity(2);

b.push(vec![7., 8., 9.]);
b.push(vec![10., 11., 12.]);

let mut c: Vec<Vec<f64>> = Vec::with_capacity(2);

// expected result:
// c: Vec<Vec<f64>> = [[1., 2., 3., 7., 8., 9.], [4., 5., 6., 10., 11., 12.] ]

Upvotes: 0

Views: 298

Answers (1)

Shepmaster
Shepmaster

Reputation: 430741

There a large number of ways to do this. One is to zip the outer vectors and then concatenate the inner vectors:

let a: Vec<Vec<f64>> = vec![vec![1., 2., 3.], vec![4., 5., 6.]];

let b: Vec<Vec<f64>> = vec![vec![7., 8., 9.], vec![10., 11., 12.]];

let c: Vec<Vec<f64>> = a
    .into_iter()
    .zip(b)
    .map(|(mut a, b)| {
        a.extend(b);
        a
    })
    .collect();

assert_eq!(c, [[1., 2., 3., 7., 8., 9.], [4., 5., 6., 10., 11., 12.]]);

See also:

Upvotes: 3

Related Questions