简体   繁体   English

C ++向量生成函数类对象

[英]c++ vector generate function class object

I have to use 'generate' function on vector to create 10 objects. 我必须在vector上使用“ generate”功能来创建10个对象。 I have class Point with constructor: 我有带构造函数的Point类:

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 . 似乎您想用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 . 在遇到实际问题之前,无需调用std::generate ,因为v已经具有Point 10个默认构造实例。

But if you really want to call it, std::generate expects as Generator a function object, ie an object with operator() . 但是,如果您真的要调用它, std::generate希望将Generator作为函数对象,即具有operator()的对象。 Point doesn't have one, and the compiler complains. Point没有一个,编译器抱怨。 Passing a lambda is a good idea, as they are such function objects: 传递lambda是一个好主意,因为它们是这样的函数对象:

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 . 您正在传递一个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). 也许您试图提供Point的构造函数作为生成器函数,但是构造函数不满足要求(它不返回任何内容),永远不要直接调用它,并且永远不能获得它的地址(也不能得到)对一个的引用)。

You must provide a separate function that simply returns points. 您必须提供一个单独的函数,该函数仅返回点。 The easiest way is to pass std::generate a lambda function. 最简单的方法是传递std::generate一个lambda函数。 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); 但是,请注意,行std::vector<Point> v(10); already creates 10 default constructed Point objects. 已经创建了10个默认构造的Point对象。 Since your randomization logic is in your default constructor, it's redundant to use std::generate in this case. 由于您的随机化逻辑位于默认构造函数中,因此在这种情况下使用std::generate是多余的。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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