What Are the Issues with a Vector-Of-Vectors

What are the Issues with a vector-of-vectors?

I shall answer with a simple analogy.

What is "better" in general out of the two things?

  1. A telephone book where each entry is a code referring to a different book that you have to find and read to discover someone's telephone number
  2. A telephone book that lists people's telephone numbers

Keeping all your data in a single big blob is more simple, more sensible, and easier on your computer's cache. A vector with N vectors inside it is much more operationally complex (remember, each of those requires a dynamic allocation and size management operations!); one vector is, well, one vector. You haven't multiplied the workload by N.

The only downside really is that to simulate 2D array access with a 1D underlying data store, you need to write a facade. Fortunately, this is very easy.

Now for the subjective part: on balance I'd say that it's worthwhile unless you're really in a rush and your code quality doesn't particularly matter.

C++: Problems with a vector of vectors of structs

The method:

myVVOfStructs.reserve(10);

does not change the size of the vector itself.
Reserve - Vector:

This function has no effect on the vector size and cannot alter its elements.

So, when you're trying to access the 6-th element with:

vector< MyStruct > tmpVector = myVVOfStructs[5];

That will produce an UB, because the myVVOfStructs[5] does not exists yet.


In order to change the size of the vector you should use the method:

mmVVOfStruct.resize(10);

Why isn't a vector of a vector guaranteed to be contiguous? (or is it?)

Each of your vector inside the vector of vectors is an individual object, and as such is responsible for it's storage. So, no, it is by no means guaranteed to be contiguous, in fact I can 't really see a situation where it could happen that the data stored in the outer vector and it's inner vectors is one contiguous block of memory ever.

2D vector issue in c++

Let me guess: you have inverted the order of rows and columns in this declaration

minesweeper:minesweeper play(columns, rows, mines, mineField);

and should be

minesweeper:minesweeper play(rows, columns, mines, mineField);


Related Topics



Leave a reply



Submit