In C++ we have functions like std::fill
or std::fill_n
which are convenient one-liner ways of filling pointer-arrays, vectors, std::array
s 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With