1

I'm new to lambdas, I made my own binary heap class with custom comparator function. It went well until I got a compilation error and I don't know how to fix.

I tried to change my line of code a bit, instead of

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

I changed to this:

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

I got the same result. How to deal with this error?

binary heap class:

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

The part of my code with a compilation error

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;
}
max66
  • 65,235
  • 10
  • 71
  • 111
Jimmy Y.
  • 91
  • 7
  • 4
    Well, yeah. `this` is a pointer to your object; it's not a function. What are you trying to do with `this( ... )`? – melpomene Jan 29 '19 at 02:31
  • I learned from Java that this(...) will call a constructor of the object. – Jimmy Y. Jan 29 '19 at 02:36
  • 3
    C++ is not Java. – melpomene Jan 29 '19 at 02:37
  • Most of your code is unnecessary. Your error can be reduced to `struct foo { void bar() { this(); } };`. – melpomene Jan 29 '19 at 02:37
  • 1
    Possible duplicate of [Can I call a constructor from another constructor (do constructor chaining) in C++?](https://stackoverflow.com/questions/308276/can-i-call-a-constructor-from-another-constructor-do-constructor-chaining-in-c) – bashrc Jan 29 '19 at 02:47

1 Answers1

0

I suppose you want to use the delegating constructor feature; so

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

or, as suggested by melpomene (thanks), you can delete this constructor and add a default value ([](int a, int b){return a - b;}) for the second argument in the other constructor.

max66
  • 65,235
  • 10
  • 71
  • 111