Set std::vector<int> to a range
You could use std::iota
if you have C++11 support or are using the STL:
std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);
or implement your own if not.
If you can use boost
, then a nice option is boost::irange
:
std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
See e.g. this question
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template<class OutputIterator, class Size, class Assignable>
void iota_n(OutputIterator first, Size n, Assignable value)
{
std::generate_n(first, n, [&value]() {
return value++;
});
}
int main()
{
std::vector<int> v; // no default init
v.reserve(14); // allocate 14 ints
iota_n(std::back_inserter(v), 14, 3); // fill them with 3...16
std::for_each(v.begin(), v.end(), [](int const& elem) {
std::cout << elem << "\n";
});
return 0;
}
Output on Ideone