crmsnfatalis crmsnfatalis - 2 months ago 24
C++ Question

stl std::generate c++, how to write the function call

So I have a programming assignment where they supply us with the header file which contains:

class SEQ{
private:
...// stuff
public:
...//constructor
string operator ( ) ( ) {
string tmp = id; int i = nd - 1;
if ( id [ i ] < '9' ) id [ i ]++;
else {
id [ i ] = '1'; bool flag = true;
for ( i--; i >= 0 && flag; i-- )
if ( id [ i ] < 'Z' ) { id [ i ]++; flag = false; }
else id [ i ] = 'A';
}
return tmp;
}
}


I am supposed to use this with std::generate on an std::vector. However, the function never gets called. I have tried writing it these ways:

vector<string> v;
for (int i = v.size(); i < in.N; i++) v.push_back("");

generate(v.begin(), v.end(), SEQ); // compiler error
generate(v.begin(), v.end(), SEQ()); // no error but does nothing

SEQ seq; // declare an instance
generate(v.begin(), v.end(), seq); // no error but does nothing
generate(v.begin(), v.end(), seq()); // compiler error algorithm line 1527 does not evaluate to a function that takes 0 arguments


I am assuming the header file they gave me does not contain any errors. How am I supposed to write this so that the function gets called?

Answer

generate takes a function pointer or a reference to an instance of a functor. The following two calls are correct. They are no-ops if the vector is empty.

// pass a default-constructed temporary instance
generate(v.begin(), v.end(), SEQ{});
// pass a named instance
SEQ seq;
generate(v.begin(), v.end(), seq);

The following works:

#include <algorithm>
#include <vector>
#include <cassert>

int main()
{
    std::vector<size_t> v(10);
    auto seq = [a = 0]() mutable { return a++; };
    std::generate(v.begin(), v.end(), seq);
    assert(v.begin() != v.end());
    for (size_t i = 0; i < v.size(); ++i)
       assert(v[i] == i);
}