Hasan Zeen
Hasan Zeen

Reputation: 157

vector of objects - how to send a parameter to the constructor?

Let us say I have the following code:

struct obj{
    int v;
    obj(int i = 1){
        v = i;
    }
};

int main(){
    vector<obj> v1(10);    // (1)
    vector<obj> v2(15);    // (2)
}

Per above:

Number (1) creates a vector that has 10 instances of obj with default v=1.
Number (2) how to send 15 as a parameter to obj so v=15???

I searched the net and found this article on this site, but it seems about more advanced things and as a novice I did not get it.

Upvotes: 5

Views: 1203

Answers (2)

Shadi
Shadi

Reputation: 1771

You can do it this way:

vector<obj> v3 (10,15);

10 is number of objects.
15 is the parameter to the constructor.

for multiple parameters, you can send multiple values as a list as follows:

vector<obj> v3 (10, {15,25} );

{15,25}. This is called an initializer list.

An alternative would be:

vector<obj> v3(10, obj(15,25));

See Baum's note. It is a good reference.

Upvotes: 4

Sid S
Sid S

Reputation: 6125

vector<obj> v1(10);     // creates a vector of 10 obj, each initialized 
                        // with the default value 1

vector<obj> v2(10, 15); // creates a vector of 10 obj, each initialized 
                        // with the value 15

If you want to pass more than one argument to the constructors :

vector<obj> v3(10, obj(15, x, y)); // creates a vector of 10 obj, each 
                                   // initialized with (15, x, y)

You would of course have to provide a constructor that takes three arguments for that to work.

Upvotes: 5

Related Questions