How to fill STL containers by means of generate_n with index increment

  • A+
Category:Languages

To fill STL containers with values that depend on their index, I usually write like the code below. Is there any way to do the same without declaring the index?

int main(){   static int N=10;   auto func = [](int idx){return idx*(idx+1)+1;};   int idx = -1;   std::list<int> lst;   std::generate_n(std::back_inserter(lst), N, [&](){idx++; return func(idx);}); } 

 


You can move the index into the lambda capture and make the lambda mutable like this (requires C++14):

std::generate_n(std::back_inserter(lst), N,     [&func, idx = -1] () mutable {idx++; return func(idx);}); 

Now you can omit the line int idx = -1;. There might be a better solution though, as sacrificing the default const qualification of the closure just to move an integer declaration from the surrounding scope into the capture isn't perfect. Still though, the scope of idx has been reduced, and if I understand your question correctly, this was the goal.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: