Search code examples
c++visual-studio-2017function-pointersheapsort

Confused about parameters for bool function pointer


I am trying to call my heapify function which is supposed to create a binary tree and heap sort it in a way all depending on my boolean function parameter.

My problem: I am not sure how to pass the function pointer in main when calling my heapify function.

My attempt in passing the values along with my code is down below (I get an error when trying to call the function: expression must be an lvalue or a function designator)

struct S {
    double x;
    int n;
    char c;
};

void heapify(S bt[], unsigned els, bool(*shouldBeBefore)(const S & a, const S & b));

int main() {
    S test[9] = { {1.1,1,'A'},{1.3,2,'B'},{1.8,3,'C'},{1.7,4,'D'},{5.1,5,'E'},{4.3,6,'F'},{3.8,7,'G'},{4.7,8,'H'},{2.7,9,'I'} };
    heapify(x, 9,&shouldBeBefore(test[0], test[1]));
    return 0;
}

bool shouldBeBefore(const S & a, const S & b) {
    if (a.x < b.x) {
        return true;
    }
    else {
        return false;
    }
}

Solution

  • Move your declaration (or entire definition) of shouldBeBefore above main where you invoke heapify. But when you invoke heapify, you just pass in the function name. heapify will invoke your shouldBeBefore function with it's own parameters.

    void heapify(S bt[], unsigned els, bool(*shouldBeBefore)(const S & a, const S & b));
    bool shouldBeBefore(const S & a, const S & b);
    
    int main()
    {
        S test[9] = { {1.1,1,'A'},{1.3,2,'B'},{1.8,3,'C'},{1.7,4,'D'},{5.1,5,'E'},
                      {4.3,6,'F'},{3.8,7,'G'},{4.7,8,'H'},{2.7,9,'I'} };
    
        unsigned int length = sizeof(test)/sizeof(test[0]); // 9
    
        heapify(S, length, shouldBeBefore);
    
        return 0;
    }
    
    bool shouldBeBefore(const S & a, const S & b) 
    {
        return (a.x < b.x);
    }
    

    In your implementation of heapify, you can invoke shouldBeBefore just like any other function:

    void heapify(S bt[], unsigned els, bool(*shouldBeBefore)(const S & a, const S & b))
    {
        ...
            if (shouldBeBefore(S[i+1], S[i]) {
                ...
            }
        ...
    }