Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

c++ - Using For Loop to Add Numbers to a Vector

I want to add numbers 1 through 10 to an empty vector using a for loop. So I know that it should look like this:

for (int i = 1; i <=10 ; i++){

//some code that adds 1 - 10 to a vector

}

After the code has ran, I should get a vector that looks like this: {1,2,3,4,5,6,7,8,9,10}.

Can someone help me please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const int N = 10;

std::vector<int> v;
v.reserve( N );

for ( int i = 1; i <= N; i++ ) v.push_back( i );

Or

const int N = 10;

std::vector<int> v( N );

int i = 1;
for ( int &x : v ) x = i++;

Or

#include <numeric>

//...

const int N = 10;

std::vector<int> v( N );

std::iota( v.begin(), v.end(), 1 );

Or

#include <algorithm>

//...

const int N = 10;

std::vector<int> v( N );

int i = 1;
std::for_each( v.begin(), v.end(), [&i]( int &x ) { x = i++; } );

Or

#include <algorithm>
#include <iterator>

//...

const int N = 10;

std::vector<int> v;
v.reserve( N );

int i = 1;
std::generate_n( std::back_inserter( v ), N, [&i] { return i++; } );

All these methods use for loop


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...