I am writing a library which employs a Vec<Vec<T>>
type to store data in column-major order (each inner Vec
represents a column). The user can create a Vec<Vec<T>>
with any row and column length but all columns are constrained to be the same length.
I need to sometimes efficiently iterate through the Vec<Vec<T>>
by row. I would like to not change the array type because most of the time I need to iterate "by column vector" (one full column vector at a time).
Unless I am missing something, Iterator::zip
is not an option because I do not know the number of column vectors in advance. Itertools::izip
and Itertools::multizip
are also not viable.
This is my sample code:
let array = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
let mut iterators: Vec<_> = array.iter().map(|x| x.iter()).collect();
for _ in 0..array[0].len() {
let values: Vec<_> = iterators.iter_mut().map(|x| x.next().unwrap()).collect();
dbg!(values);
}
Should I define a mutable values
vector before starting the iterations to avoid allocations at each cycle, or will the compiler take care of this optimization anyway? What is the easiest method to find it myself?
Are there more efficient / idiomatic solutions?