0

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 
4
  • 3
    Foo::Foo(std::initializer_list<int> init_list) : a(init_list) {} Commented Apr 12, 2016 at 9:44
  • For the record, this is not the "new" standard any more.. there have been 1.5 newer ones since ;) Commented Apr 12, 2016 at 10:25
  • @LightnessRacesinOrbit yea you got right haha :) Commented Apr 12, 2016 at 10:58
  • 1
    That's an std::initializer_list, not an initiali(s/z)er list or an "initialization list". I don't want to be pedantic for its own sake, but the Standard uses such similar terms for different things that we have no choice! Commented Apr 12, 2016 at 11:39

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Big thanks for your answer it is really bizzare that I didn't find it.
Yep especially as the answer is right there in the "Related" questions list!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.