Parse complex vector into vectors of tuples

⚓ Rust    📅 2026-03-18    👤 surdeus    👁️ 1      

surdeus

I have a vector of data stored as:
[1,2,3,4,a,b,c,d,5,6,7,8,e,f,g,h....]
I need to return a vector of vector of tuples Vec<Vec<(,)>>
where each individual vector looks like:
[(1,a), (5,e)...]
[ (2,b), (6,f)...]
[(3,c), (7,g)...]
(4,d),(8,h)...]

I need a reasonably efficient means of doing so. I have a solution but I'm doing more copies than necessary (I'm still wrapping my head around some of these concepts). What can I do to tighten this up?

pub fn element_data(&self) -> Vec<Vec<(f32,f32)>> {
        let mut results: Vec<Vec<(f32,f32)>> = Vec::new();
        // extract each elements data
        let num_elements = 4;

        for element in 0..=num_elements {
            // iterate over the data and extract the current elements data, skipping over other
            //elements [0,3,7,...],
            let datavec: Vec<f32> = self.data
                .iter()
                .skip((element) as usize)
                .step_by(num_elements as usize)
                .copied()
                .map(|x| /* modify data here */ x)
                .collect_vec();

            let datapairs: Vec<(f32,f32)> = datavec
                .into_iter()
                .tuples::<(_,_)>()
                .collect::<Vec<_>>();

            results.push(datapairs); // save the resulting vector
        }
        results // return vector of vectors
    }

1 post - 1 participant

Read full topic

🏷️ Rust_feed