My first choice (even in C++11) would be
boost::counting_iterator
:
std::vector<int> ivec( boost::counting_iterator<int>( 0 ),
boost::counting_iterator<int>( n ) );
or if the vector was already constructed:
std::copy( boost::counting_iterator<int>( 0 ),
boost::counting_iterator<int>( ivec.size() ),
ivec.begin() );
If you can't use Boost: either std::generate
(as suggested in
other answers), or implement counting_iterator
yourself, if
you need it in various places. (With Boost, you can use
a transform_iterator
of a counting_iterator
to create all
sorts of interesting sequences. Without Boost, you can do a lot
of this by hand, either in the form of a generator object type
for std::generate
, or as something you can plug into a hand
written counting iterator.)