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

C++StlConstructorInitializer List

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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 - C++

I think you mean this:

struct test {
   std::vector<int> v;
   test(int value) : v( 100, value ) {}
};

Solution 3 - C++

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 - C++

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

Solution 5 - C++

You can do that with std::vector constructor:

vector(size_type count, 
                 const T& value,
                 const Allocator& alloc = Allocator());

Which takes count and value to be repeated.

If you want to use initializer lists you can write:

const int x = 5;
std::vector<int> vec {x, x, x, x, x, x, x, x, x, x};

Solution 6 - C++

can you post what you are doing

 int i = 100;
vector<int> vInts2 (10, i);

vector<int>::iterator iter;
for(iter = vInts2.begin(); iter != vInts2.end(); ++iter)
{
	cout << " i " << (*iter) << endl;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXavierView Question on Stackoverflow
Solution 1 - C++Ed S.View Answer on Stackoverflow
Solution 2 - C++David Rodríguez - dribeasView Answer on Stackoverflow
Solution 3 - C++Mahmoud Al-QudsiView Answer on Stackoverflow
Solution 4 - C++AgusView Answer on Stackoverflow
Solution 5 - C++Rafał RawickiView Answer on Stackoverflow
Solution 6 - C++nate_weldonView Answer on Stackoverflow