Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a vector with non-trivial initial values?

Tags:

c++

stl

I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:

void IndexArray( unsigned int length, std::vector<unsigned int>& v )
{
    v.resize(length);
    for ( unsigned int i = 0; i < length; ++i )
    {
        v[i] = i;
    }
}

But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and not using Boost)?

like image 885
andreas buykx Avatar asked Oct 16 '08 08:10

andreas buykx


1 Answers

You can use the generate algorithm, for a more general way of filling up containers:

#include <iostream>
#include <algorithm>
#include <vector>

struct c_unique {
   int current;
   c_unique() {current=0;}
   int operator()() {return ++current;}
} UniqueNumber;


int main () {
  vector<int> myvector (8);
  generate (myvector.begin(), myvector.end(), UniqueNumber);

  cout << "\nmyvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}

This was shamelessly lifted and edited from cplusplusreference.

like image 150
moogs Avatar answered Oct 15 '22 21:10

moogs