Initializing class member (vector) in constructor via initialization list

前端 未结 2 1970
一整个雨季
一整个雨季 2021-01-28 05:37

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

vector  a {3, 5, 6, 2};

I am

相关标签:
2条回答
  • 2021-01-28 06:31

    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

    0 讨论(0)
  • 2021-01-28 06:37

    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

    0 讨论(0)
提交回复
热议问题