-1

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.

WannabeArchitect
  • 1,058
  • 2
  • 11
  • 22
  • 1
    Sidenote: Clearing an already empty vector has no effect. It does _not_ initialize the vector. This is done in the constructor which is invoked automatically. – Lukas-T Jan 16 '21 at 07:20
  • 1
    vectors store their size internally (which you can get using the `.size()` method), so storing the size separately in your class is at best redundant, and potentially buggy. Just query the vector when you want to know it's size. – john Jan 16 '21 at 07:22

2 Answers2

3

std::vector have a constructor overload which takes a size for the vector.

You can use this to initialize your vector:

MyClass::MyClass(int size)
    : vector_size(size),
      vector_2d(size)
{
}

This will initialize vector_2d to have size elements. Each element is a default-constructed std::vector<int> object (the type of each element).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

In your code, vector_2d is default-initialzied as empty std::vector firstly (thus calling of clear() is superfluous), then gets modified in the body of constructor.

You can initialize it directly in member initializer list. E.g.

// initializa vector_2d as containing _vector_size empty std::vector<int>
MyClass::MyClass(int _vector_size):
vector_size(_vector_size), vector_2d(_vector_size) {}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405