问题
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?
回答1:
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
回答2:
You can do this by simply pushing value in the vector.. as the vector has a property of push_back to add value in it.
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
for(int i=1 ; i<=10 ;i++)
myvector.push_back(i);
return 0;
}
the vector will then contain : {1,2,3,4,5,6,7,8,9,10}
For more You can read this references: http://www.cplusplus.com/reference/vector/vector/push_back/
来源:https://stackoverflow.com/questions/27847128/using-for-loop-to-add-numbers-to-a-vector