Can I initialize an STL vector with 10 of the same integer in an initializer list?
Solution 1:
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);
Solution 2:
I think you mean this:
struct test {
std::vector<int> v;
test(int value) : v( 100, value ) {}
};
Solution 3:
If you're using C++11 and on GCC, you could do this:
vector<int> myVec () {[0 ... 99] = 1};
It's called ranged initialization and is a GCC-only extension.
Solution 4:
The initialization list for vector is supported from C++0x. If you compiled with C++98
int number_of_elements = 10;
int default_value = 1;
std::vector<int> vec(number_of_elements, default_value);