Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize an STL vector with 10 of the same integer in an initializer list?

Can I initialize an STL vector with 10 of the same integer in an initializer list? My attempts so far have failed me.

like image 432
Xavier Avatar asked Apr 19 '12 22:04

Xavier


People also ask

How do you initialize a vector to a specific size?

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.

How do you declare a vector by default value?

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


2 Answers

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); 
like image 126
Ed S. Avatar answered Oct 09 '22 01:10

Ed S.


I think you mean this:

struct test {
   std::vector<int> v;
   test(int value) : v( 100, value ) {}
};
like image 21
David Rodríguez - dribeas Avatar answered Oct 09 '22 01:10

David Rodríguez - dribeas