What way to store n.m matrix is more efficient? To create a vector of n vectors of size m or to a create big vector of size n.m?
How is a vector of vectors stored in the memory? Does it contains only references/pointers or whole vectors?
Asked
Active
Viewed 62 times
1

IBazhov
- 175
- 8
-
1I would prefer `std::vector<>(n * m)`. The vector itself is a structure of fixed size which stores size, length, and a pointer to data memory. The data memory is (re-)allocate on heap whenever resizing beyond capacity is requested. – Scheff's Cat Aug 06 '17 at 05:10
1 Answers
4
It's more efficient to use a single vector of size N x M. This way all the memory is contiguous, and there is only a single pointer to all of it, rather than N pointers.
A vector of vectors is stored as a pointer to an array of pointers, each of which points to an array of values.

John Zwinck
- 239,568
- 38
- 324
- 436
-
3Apparently, the answer is not as obvious. https://stackoverflow.com/questions/33093860/using-nested-vectors-vs-a-flatten-vector-wrapper-strange-behaviour. – R Sahu Aug 06 '17 at 05:13