Willis Zawisa
Willis Zawisa

Reputation: 129

How to fill a vector with a range?

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

Answers (5)

juanchopanza
juanchopanza

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

David G
David G

Reputation: 96810

You can use std::iota():

std::vector<int> v(10);
std::iota(v.begin(), v.end(), 1);

Upvotes: 7

Vlad from Moscow
Vlad from Moscow

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

Luchian Grigore
Luchian Grigore

Reputation: 258608

Another using generate:

vector<int>test(10);
int x = 0;
std::generate(test.begin(), test.end(), [&]{ return x++; }); 

Upvotes: 6

Gabriel
Gabriel

Reputation: 3594

vector<int> vInts;
for (int i=1;i<=10;++i){
    vInts.push_back(i);
}

Upvotes: 1

Related Questions