Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use std::fill to populate vector with increasing numbers

Tags:

c++

stl

I would like to fill a vector<int> using std::fill, but instead of one value, the vector should contain numbers in increasing order after.

I tried achieving this by iterating the third parameter of the function by one, but this would only give me either vectors filled with 1 or 2 (depending of the position of the ++ operator).

Example:

vector<int> ivec; int i = 0; std::fill(ivec.begin(), ivec.end(), i++); // elements are set to 1 std::fill(ivec.begin(), ivec.end(), ++i); // elements are set to 2 
like image 233
BlackMamba Avatar asked Jul 17 '13 08:07

BlackMamba


People also ask

How do you increment a vector value?

Read a value into x , use that value as index into the vector, and increase the value at that index. So if the input for x is 1 , then it's equivalent to vec[1]++ , that is the second (remember that indexes are zero based) will be increased by one.


1 Answers

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. 
like image 60
BoBTFish Avatar answered Oct 14 '22 14:10

BoBTFish