Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for std::generate, can passed function use index?

Tags:

c++

vector

A little hard to phrase in a question so I will use an example. Lets say I do:

generate(myvec.begin(), myvec.end(), func())

Can I have it so that func() can read the index that generate is up to such that:

int func()
{
   if(index<2)
       return 1;
   else
       return 2;
}

such that myvec[0]=1, myvec[1]=1, myvec[2]=2, myvec[3]=2,..., myvec[N]=2?

like image 880
postelrich Avatar asked May 16 '26 21:05

postelrich


2 Answers

The short answer is "no, not directly". It can create its own variable that should track with the index, but (in a case like this) there's simply no access to the index itself.

Under the circumstances, I'd almost certainly just use std::fill twice:

std::fill_n(myVec.begin(), 2, 1);
std::fill(myVec.begin()+2, myVec.end(), 2);

Shorter, and simpler.

like image 151
Jerry Coffin Avatar answered May 19 '26 10:05

Jerry Coffin


Yes, if you use a function object as the generator (as juan points out, it is questionable whether this solution is guaranteed to work by the standard! Exercise caution and use Jerry's method.):

class mygenerator {
 public:
  mygenerator() : hits(0) {}

  int operator()() {
      hits++; 
      return (hits <= 2 ? 1 : 2);
  }

 private:
  int hits;
} 

...

mygenerator mg1;
std::generate(myvec.begin(), myvec.end(), mg1);
like image 44
us2012 Avatar answered May 19 '26 11:05

us2012



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!