use std::fill to populate vector with increasing numbers

Solution 1:

Preferably use std::iota like this:

std::vector<int> v(100) ; // vector with 100 ints.
std::iota (std::begin(v), std::end(v), 0); // Fill with 0, 1, ..., 99.

That said, if you don't have any c++11 support (still a real problem where I work), use std::generate like this:

struct IncGenerator {
    int current_;
    IncGenerator (int start) : current_(start) {}
    int operator() () { return current_++; }
};

// ...

std::vector<int> v(100) ; // vector with 100 ints.
IncGenerator g (0);
std::generate( v.begin(), v.end(), g); // Fill with the result of calling g() repeatedly.

Solution 2:

You should use std::iota algorithm (defined in <numeric>):

  std::vector<int> ivec(100);
  std::iota(ivec.begin(), ivec.end(), 0); // ivec will become: [0..99]

Because std::fill just assigns the given fixed value to the elements in the given range [n1,n2). And std::iota fills the given range [n1, n2) with sequentially increasing values, starting with the initial value and then using ++value.You can also use std::generate as an alternative.

Don't forget that std::iota is C++11 STL algorithm. But a lot of modern compilers support it e.g. GCC, Clang and VS2012 : http://msdn.microsoft.com/en-us/library/vstudio/jj651033.aspx

P.S. This function is named after the integer function from the programming language APL, and signifies a Greek letter iota. I speculate that originally in APL this odd name was chosen because it resembles an “integer” (even though in mathematics iota is widely used to denote the imaginary part of a complex number).

Solution 3:

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

Solution 4:

I've seen the answers with std::generate but you can also "improve" that by using static variables inside the lambda, instead of declaring a counter outside of the function or creating a generator class :

std::vector<int> vec;
std::generate(vec.begin(), vec.end(), [] {
    static int i = 0;
    return i++;
});

I find it a little more concise