I have a pattern in which I want to fill an array:
even indices value = -1
odd indices value = 1
I currently achieve it like this:
#include <array>
#include <algorithm>
using namespace std;
int generator(){
static int i = 1;
i *= -1;
return i;
}
std::array<int ,64> arr;
std::generate(arr.begin(), arr.end(), generator);
Edit: Current implementation has a caveat - returned value of generator
doesn't depend on iteration's object index.
Is there a way to pass current index to the generator
function so it's output will depend on this index?
Your generator
function has a static
local variable, which preserves its state across every call. This means that if you use generator
in a different call it remembers its old state, which might not be what you want.
You can fix this by writing a function that gives you a "generator" every time you call it. Note that the returned value (i.e. the generator itself) is just a mutable
lambda, so that the value of i
is preserved across multiple calls to that lambda.
auto gen()
{
return [i = -1]() mutable
{
i *= -1;
return i;
};
}
// usage ...
std::generate(arr.begin(), arr.end(), gen());
Here's a demo.
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