Set std::vector<int> to a range

Andreas picture Andreas · Aug 15, 2012 · Viewed 38.8k times · Source

What's the best way for setting an std::vector<int> to a range, e.g. all numbers between 3 and 16?

Answer

juanchopanza picture juanchopanza · Aug 15, 2012

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));