1

I see a code on a website. There i see a function that receive two parameter but when this function is called, here didn't pass any parameter. I can't understand what actually happened here.

My question is how this function work?

sort(arr, arr+n, Sort_activity); Here sort_activity is a function.

Here is the full code:


#include <bits/stdc++.h>

using namespace std; 
#define N 6     


struct Activity 
{ 
    int start, finish; 
}; 

 
**bool Sort_activity(Activity s1, Activity s2) 
{ 
    return (s1.finish< s2.finish); 
}** 


void print_Max_Activities(Activity arr[], int n) 
{ 
    
    sort(arr, arr+n, Sort_activity); 

    cout<< "Following activities are selected \n"; 

   
    int i = 0; 
    cout<< "(" <<arr[i].start<< ", " <<arr[i].finish << ")\n"; 

   
    for (int j = 1; j < n; j++) 
    { 
        
        if (arr[j].start>= arr[i].finish) 
        {    
            cout<< "(" <<arr[j].start<< ", "<<arr[j].finish << ") \n"; 
            i = j; 
        } 
    } 
} 


int main() 
{ 
    Activity arr[N];
    for(int i=0; i<=N-1; i++)
    {
        cout<<"Enter the start and end time of "<<i+1<<" activity \n";
        cin>>arr[i].start>>arr[i].finish;
    }

    print_Max_Activities(arr, N); 
    return 0; 
}
  • 2
    How did you know the function is called without parameters? – MikeCAT Jun 16 '21 at 16:18
  • It's not called without parameters. Its address is passed to `std::sort()`, which then calls it with the elements to be sorted. Read up about callables, predicates, functors, etc I guess. – underscore_d Jun 16 '21 at 16:18
  • 1
    note that `Sort_activity` should take its parameters by const reference – Alan Birtles Jun 16 '21 at 16:19
  • 1
    In the call to `sort`, the third argument, `Sort_activity`, is a pointer to the function. The `sort` function calls it whenever it needs to compare two objects. You don’t need `&` to get the address of a function; the name by itself is treated as a pointer. – Pete Becker Jun 16 '21 at 16:20
  • See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Jun 20 '21 at 08:46

0 Answers0