Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an STL-like function to fill an array with some function of the index?

Tags:

c++

c++11

stl

In C++ we have functions like std::fill or std::fill_n which are convenient one-liner ways of filling pointer-arrays, vectors, std::arrays and other containers with values. Some containers also have their own fill methods to allow filling with a constant value. There are also the functions std::generate{_n} and std::iota, the former of which allows filling the elements using a generator function and the latter of which fills the range with indices.

What I am looking for is a similar solution - preferrably a one-liner solution and defined in the standard library - that allows filling the container with some function of the index. For example, this would be a solution for an array:

std::array<int, 100> arr;
for (std::size_t i = 0; i < 100; i++)
    arr[i] = f(i);

where f(std::size_t i) is some function of the index.

Is there an integrated way of doing this?

like image 621
HerpDerpington Avatar asked Oct 19 '25 03:10

HerpDerpington


1 Answers

You could use a stateful lambda:

std::array<int, 100> arr;   
std::generate(arr.begin(), arr.end(), [i = std::size_t(0)]() mutable {return f(i++);});

But I think it makes the code more complex than it needs to be. Using a plain loop might be the best option.

like image 97
HolyBlackCat Avatar answered Oct 21 '25 17:10

HolyBlackCat



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!