FieryCod
FieryCod

Reputation: 1710

Initializing class member (vector) in constructor via initialization list

The C++11 standard gives an opportunity to initialize a vector with an initialization list like this.

vector <int> a {3, 5, 6, 2};

I am just wondering if it is possible to initialize a vector which is a member of class in a constructor via initialization list.

I looked for such a thing but I did not find it on the Internet or here on Stack Overflow, so I thought that I should ask for it. I hope that not only I, but also others will find it useful.

I do not want to make vector a static member of a class.

The class should look like this:

class Foo
{
    public:
        vector <int> myvector;
        //Here should be a constructor 
};

It could be used like this:

Foo aa{1, 2, 3, 6, 1}; // it should initialize a vector 

Upvotes: 0

Views: 2694

Answers (2)

Quentin
Quentin

Reputation: 63114

Yes ! You just need to take in an std::initializer_list and initialize your vector with it.

struct Foo {
    Foo(std::initializer_list<int> l)
    : _vec{l} { }

    std::vector<int> _vec;
};

Live on Coliru

Upvotes: 3

rep_movsd
rep_movsd

Reputation: 6895

You need to define a constructor for Foo that takes an initializer list, and pass it to the vector.

See http://en.cppreference.com/w/cpp/utility/initializer_list for an example that does exactly what you need

Upvotes: 1

Related Questions