vendredi 14 août 2020

Lambda function throwing error if return type is changed from auto to bool

I was practicing lambda functions in C++, following code works fine


void insertionSort(int* a, int size, bool reverse=false) {
    auto comp = [](int a, int b, bool reverse) {
        return reverse ? a > b : b < a;
    };
    
    for (int i = 0; i < size; i++) {
        int current = a[i];
        cout << current <<endl;
        int j = i-1;
        while (j >= 0 && comp(current, a[j], reverse)) {
           a[j+1] = a[j]; //shift right
           j--;
        }
        a[j+1] = current;
    }
    show(a, size); //another function which prints all elements of a
}

but if I change

    auto comp = [](int a, int b, bool reverse) {

with

    bool comp = [](int a, int b, bool reverse) {

GCC compiler throws following error while compiling error: 'comp' cannot be used as a function 29 | while (j >= 0 && comp(current, a[j], reverse)) {

So is this expected? What is general rule? Shall I always specify return type as auto?

Aucun commentaire:

Enregistrer un commentaire