I have a member variable two-dimensional vector in a class, like this:
#include <vector>
...
class MyClass {
private:
int vector_size;
std::vector<std::vector<int> > vector_2d;
public:
MyClass(int _vector_size);
~MyClass();
} // class MyClass
I want to know the best way of implementing the constructor MyClass(int _vector_size)
to fully initialize the vector to consist of _vector_size
empty vectors. The code I have now is as follows (and this works perfectly fine in a little toy program I wrote to test correctness), but I feel like the declaration of temp_vec
and the constant temp_vec.clear()
might be a little redundant.
MyClass::MyClass(int _vector_size):
vector_size(_vector_size)
{
// initialize vector_2d
vector_2d.clear();
// push initialized 1D vectors
for (int i = 0; i < vector_size; ++i) {
std::vector<int> temp_vec;
temp_vec.clear();
vector_2d.push_back(temp_vec);
}
}
I have also checked other posts such as this, this, and this, but I think my question differs in that I want a vector of specified size that consists of vectors of unspecified size.