c++in-class-initializationbraced-init-list

In-class initialization of vector with size


struct Uct
{
    std::vector<int> vec{10};
};

The code above creates vector that contains single element with value 10. But I need to initialize the vector with size 10 instead. Just like this:

std::vector<int> vec(10);

How can I do this with in-class initialization?


Solution

  • I think there are 2 aswers:

    std::vector<int> vec = std::vector<int>(10);
    

    as said in the comments and:

    std::vector<int> vec{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

    this is less preferable since it's less readable and harder to adjust later on, but I think it's faster (before c++17) because it doesn't invoke a move constructor as said in the comments.

    That being said Uct(): vec(10){}; is also a perfectly viable option with the same properties(I think).