-7

Are there any problems associated with

vector< vector<int> > v(m, vector<int>(n));

Is it safer to write:

vector< vector<int> > v(m);
for (size_t i=0; i<m; i++)
    v[i].resize(n);
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
user31264
  • 6,557
  • 3
  • 26
  • 40

1 Answers1

6

Yes, it is safer, especially if the second dimension, n was very large. The resizing approach would be preferred in memory limited, embedded systems programming. Take the example of

vector< vector<int> > v(2, vector<int>(1'000'000));

Constructing the 2D vector of vectors would (for most compilers) require an additional 4'000'000 bytes (32 bit ints) compared to the resizing approach as it would create a vector of 1,000,000 needed to initialize the vectors. This is required because the vector<int>(1'000'000) must be constructed. It is then used to initialize each of the m row vectors. After execution it is destroyed so the increased memory requirement is short lived. Thus, I would prefer the second approach which does not require construction of an initializing vector.

That said, I quite agree with the point that a vector of vectors is a particularly bad approach to creating dynamic, 2D vectors unless each row is to have variable numbers of columns.

See my answer here which shows a short, efficient, class that can be used for 2D dynamic vectors. Statically declared 2-D array C++ as data member of a class

doug
  • 3,840
  • 1
  • 14
  • 18
  • 1
    This is either wrong or so poorly worded that it's wrong. Both options will consume the same storage in the same block sizes. – user4581301 Jan 05 '19 at 18:50
  • 1
    @user4581301 Only after the formation of the vector of vectors. During formation it requires more memory. – doug Jan 05 '19 at 18:52
  • @doug Presumably you're talking about the ctor argument. I don't know whether it is copied _n-1_ times then moved at the end (which removes your concern) but it is certainly possible. Worth investigating. – Lightness Races in Orbit Jan 05 '19 at 18:53
  • @LightnessRacesinOrbit Construction of `vector(n)` used to initialize. While not required, what compiler doesn't? – doug Jan 05 '19 at 18:54
  • Actually thinking about it, that arg is `const T&` not `T&&` so it must be copied for all elements. So, you are correct, there is (briefly) one additional "row" in memory. – Lightness Races in Orbit Jan 05 '19 at 18:56
  • I see where you are coming from. Recommend editing paragraphs three and four to make where the extra row is coming from brutally clear. – user4581301 Jan 05 '19 at 18:58
  • 1
    Yep agreed answer could be clearer but have upvoted pre-emptively as the argument is sound. – Lightness Races in Orbit Jan 05 '19 at 18:58
  • @LightnessRacesinOrbit Good point about `const T&` – doug Jan 05 '19 at 18:59