简体   繁体   中英

c++ vector generate function class object

I have to use 'generate' function on vector to create 10 objects. I have class Point with constructor:

Point(){
        this->x=rand()%100;
        this->y=rand()%100;
};

Then I create a vector and use 'generate' function:

vector<Point> v (10);
generate (v.begin(), v.end(), Point());

When I compile it I receive this error:

Type 'Point' does not provide a call operator

I don't know why.

It looks like you want to fill the vector with default constructed instances of Point .

Before coming to your actual issue, that call to std::generate is unnecessary, as v will already have 10 default constructed instances of Point .

But if you really want to call it, std::generate expects as Generator a function object, ie an object with operator() . Point doesn't have one, and the compiler complains. Passing a lambda is a good idea, as they are such function objects:

std::generate(v.begin(), v.end(), []() {
    return Point{};
});

The prototype for the generator function is described here . It must be a function that returns the next value to generate. You are passing a single default constructed instance of Point . Perhaps you were trying to provide Point 's constructor as the generator function, but a constructor does not meet the requirement (it doesn't return anything), should never be called directly, and it's address can never be obtained (neither can you get a reference to one).

You must provide a separate function that simply returns points. The easiest way is to pass std::generate a lambda function. You would do something like this :

std::vector<Point> v(10);
std::generate(v.begin(), v.end(), []() { return Point{}; });

However, note that the line std::vector<Point> v(10); already creates 10 default constructed Point objects. Since your randomization logic is in your default constructor, it's redundant to use std::generate in this case.

you need a function that generates the Points

Point RandomPoint() { return Point(); }

int main(int argA, char** argV)
{
    vector<Point> v(10);

    generate(v.begin(), v.end(), RandomPoint);

    return  0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM