About this blog

Save duplicate questions from disappearing from Google

In-class initialization of vector with size

Question

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?

Answer

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).