Reputation: 129
How would I fill a vector with the numbers from 1 to 10 in C++? I have this but its not working.
vector<int>test(10);
test={ 1, 10 };
Upvotes: 0
Views: 10634
Reputation: 227410
Many options. For example,
vector<int> test{1,2,3,4,5,6,7,8,9,10};
or
std::vector<int> test;
test.reserve(10); // prevent some reallocations
for (int i = 1; i < 11; ++i)
test.push_back(i);
or
std::vector<int> test(10);
std::iota(test.begin(), test.end(), 1);
Upvotes: 3
Reputation: 96810
You can use std::iota()
:
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 1);
Upvotes: 7
Reputation: 310980
You could use standard algorithm std::iota
declared in header <numeric>
For example
#include <numeric>
#include <vector>
//...
std::vector<int> v( 10 );
std::iota( v.begin(), v.end(), 1 );
Upvotes: 1
Reputation: 258608
Another using generate
:
vector<int>test(10);
int x = 0;
std::generate(test.begin(), test.end(), [&]{ return x++; });
Upvotes: 6