I would like to fill a vector
using std::fill
, but instead of one value, the vector should contain numbers in increasing order after.
In terms of performance you should initialize the vector with use of reserve()
combined with push_back()
functions like in the example below:
const int numberOfElements = 10;
std::vector<int> data;
data.reserve(numberOfElements);
for(int i = 0; i < numberOfElements; i++)
data.push_back(i);
All the std::fill
, std::generate
, etc. are operating on range of existing vector content, and, therefore the vector must be filled with some data earlier. Even doing the following: std::vector<int> data(10);
creates a vector with all elements set to its default value (i.e. 0 in case of int
).
The above code avoids to initialize vector content before filling it with the data you really want. Performance of this solution is well visible on large data sets.
If you'd rather not use C++11 features, you can use std::generate:
#include <algorithm>
#include <iostream>
#include <vector>
struct Generator {
Generator() : m_value( 0 ) { }
int operator()() { return m_value++; }
int m_value;
};
int main()
{
std::vector<int> ivec( 10 );
std::generate( ivec.begin(), ivec.end(), Generator() );
std::vector<int>::const_iterator it, end = ivec.end();
for ( it = ivec.begin(); it != end; ++it ) {
std::cout << *it << std::endl;
}
}
This program prints 0 to 9.
There is another option - without using iota. For_each + lambda expression can be used:
vector<int> ivec(10); // the vector of size 10
int i = 0; // incrementor
for_each(ivec.begin(), ivec.end(), [&](int& item) { ++i; item += i;});
Two important things why it's working: