[Solved] Does an array of vectors form a 2D vector?


No, but it gives similar behaviour. So what you have created is a pointer to an array of vectors. So you will end up with this:

adj[0] = []
adj[1] = []
...
adj[number_nodes] = []

and doing a push_back is a legitimate way to add to the vectors:

adj[0].push_back(some_num) -->  adj[0] = [some_num]

But this is a terrible way to approach this! Why?

  • You are using raw memory that you will have to manage and make sure you delete.
  • You cant use any of the awesome std::vector functionality on the first dimension of the matrix.
  • There is no good way to figure out the size of the vector unless you know about the variable number_of_nodes.
  • … A long list, but you get it.

You can already see that a std::vector can be used as a 1D matrix. So use 2 vectors:

std::vector<std::vector<int>> Matrix2D;

If you need an initial size in some dimension then you can do this:

std::vector<std::vector<int>> Matrix2D(number_of_nodes, std::vector<int>());

Or this:

Matrix2D.resize(number_of_nodes);

Or if that size is fixed at compile time then you could even do this:

const int number_of_nodes = 10;
std::array<std::vector<int>, number_of_nodes> Matrix2D;

Or go extra big and get a library for Matrix use like Eigen.

8

solved Does an array of vectors form a 2D vector?