1

I have this struct

struct myStruct {
    int a;
    int b;
    }

I want to create a vector <vector<myStruct> > V and initialize it to n empty vectors of type vector<myStruct>

I'm trying to use the the fill constructor like this:

vector<edge> temp;
vector<vector<edge> > V(n, temp);

This code works fine in main, but when I have V inside a class how can I do that inside the class constructor.

EDIT: when I do it in my class constructor I get the following error:
no match for call to '(std::vector<std::vector<edge> >) (int&, std::vector<edge>&)'

the code generating the error is:

vector<myStruct> temp;
V(n,  temp); // n is a parameter for the constructor
Moha the almighty camel
  • 4,327
  • 4
  • 30
  • 53

3 Answers3

3

First, note that temp is not necessary: your code is identical to

vector<vector<edge> > V(n);

Now to your main question: When your vector is inside a class, use initializer list if the member is non-static, or initialize the member in the declaration part if it is static.

class MyClass {
    vector<vector<edge> > V;
public:
    MyClass(int n) : V(n) {}
};

or like this:

// In the header
class MyClass {
    static vector<vector<edge> > V;
    ...
};

// In a cpp file; n must be defined for this to work
vector<vector<edge> > MyClass::V(n);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Just omit temp. The constructor for the class that V is inside should look like:

MyClass(size_t n) : V(n) {}
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
0
class A
{
private:
    std::vector<std::vector<myStruct>> _v;
public:
    A() : _v(10) {} // if you just want 10 empty vectors, you don't need to supply the 2nd parameter
    A(std::size_t n) : _v(n) {}
    // ...
};

You use initializer lists for this kind of initialization.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42