gpt4 book ai didi

c++ - 错误 : expression cannot be used as an function

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:28 25 4
gpt4 key购买 nike

我是 lambda 的新手,我制作了自己的带有自定义比较器函数的二进制堆类。一切顺利,直到出现编译错误,我不知道如何修复。

我试着稍微改变一下我的代码行,而不是

this(capacity, [](int a, int b){return a - b;});

我改成了这样:

function<int(int, int)> cmp = [](int a, int b){return a - b;};
this(capacity, cmp);

我得到了相同的结果。如何处理这个错误?

二叉堆类:

class binaryheap
{
private:
int *heap;
int size;
int capacity;
function<int(int, int)> cmp;
int parent(int i);
int left_child(int i);
int right_child(int i);
void swap(int *a, int *b);
void heapify(int i);
public:
binaryheap(int capacity);
binaryheap(int capacity, const function<int(int, int)>& cmp);
~binaryheap();
bool empty();
int heap_size() const;
int get_root() const;
int extract_root();
void decrease_key(int i, int value);
void insert_key(int key);
void delete_key(int i);
};

我的代码有编译错误的部分

binaryheap::binaryheap(int capacity)
{
this(capacity, [](int a, int b){return a - b;});//binaryheap.cpp:51:58: error: expression cannot be used as a function
}

binaryheap::binaryheap(int capacity, const function<int(int, int)>& cmp)
{
this->capacity = capacity;
this->heap = new int[capacity + 1];
this->size = 0;
this->cmp = cmp;
}

最佳答案

我想你想使用委托(delegate)构造函数功能;所以

 binaryheap::binaryheap (int capacity)
: binaryheap{capacity, [](int a, int b){return a - b;}}
{ }

或者,按照 melpomene 的建议(谢谢),您可以删除此构造函数并为另一个构造函数中的第二个参数。

关于c++ - 错误 : expression cannot be used as an function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54412991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com