Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...