Can I initialize an STL vector with 10 of the same integer in an initializer list? My attempts so far have failed me.
Using the fill() Method The fill() function, as the name suggests, fills or assigns all the elements in the specified range to the specified value. This method can also be used to initialize vectors in C++. The fill() function accepts three parameters begin and end iterators of the range and the value to be filled.
Specifying a default value for the Vector: In order to do so, below is the approach: Syntax: // For declaring vector v(size, default_value); // For Vector with a specific default value // here 5 is the size of the vector // and 10 is the default value vector v1(5, 10);
Use the appropriate constructor, which takes a size and a default value.
int number_of_elements = 10; int default_value = 1; std::vector<int> vec(number_of_elements, default_value);
I think you mean this:
struct test {
std::vector<int> v;
test(int value) : v( 100, value ) {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With