1

How to initialize and allocate size for 2D vector member variable using a member function at run-time?

Is there something wrong with this approach?

class A {

vector<vector<int>> m_matrix;

// trying to resize without using explicit resize
// using the constructor of 2D vectors at run time
// want the code to look simpler and avoid new/pointers
void initialize_matrix(int row, int column) {
  m_matrix = std::move(vector<vector<int>>(row, vector<int>(column, DEFAULT_VALUE)));
}
}
Chetan Dugar
  • 63
  • 1
  • 5

1 Answers1

0

The answer to your question is yes that will work fine. It uses move to guard against the compiler mistakenly using copy-assignment which is a nice touch.

You seem to be asking for suggestions though, so I'd suggest that vector<vector<int>> is a poor choice given that all the sub-vectors are the same size. You might consider using a single vector. I looked for an example of using a single vector to replace a vector-of-vectors and the simplest thing I could find on http://stackoverflow.com was this: https://stackoverflow.com/a/37868317/2642059 There's a little bit better write up here though: http://upcoder.com/2/efficient-vectors-of-vectors

Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288