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
1
  • 1
    Use an initializer list. Commented Nov 1, 2013 at 13:18

3 Answers 3

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);
2
  • in case I can't use an initializer list ? my constructor takes a file, reads data and then need to initialize, how can I do that ? Commented Nov 9, 2013 at 23:49
  • 1
    @Mhd.Tahawi If you cannot use initializer list, you can use an assignment inside the constructor's body: MyClass(int n) {V = vector<vector<edge> >(n); } Commented Nov 9, 2013 at 23:55
2

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

MyClass(size_t n) : V(n) {}
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.