How to add vectors inside vectors

So I have a vector [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
How would I add the elements inside the vector? like 1+2+3+4+5+6+7+8+9+10?

let vec = <your-vector-vectors-here>;

let sum = vec.into_iter().flatten().sum();

That should do it. The key is the flatten() method.

EDIT: And whether you choose iter() or into_iter() on the original vector depends on your scenario. iter() if you need the original vector later again for something else, into_iter() if you don't (i.e. into_iter() takes ownership of the vector).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.