Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a C++ array with numbers according to a pattern

Tags:

c++

lambda

c++17

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?

like image 852
joepol Avatar asked Sep 15 '25 16:09

joepol


1 Answers

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.

like image 142
cigien Avatar answered Sep 17 '25 06:09

cigien