Using a function as the default value

I know about default values, but what about default functions as parameters? I want to sort Ascending by default if not specified. I know i can overload it, by writing another function with 2 parameters. Just wondering if default function is even a thing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

 void SelectionSort(vector<int> &anVector, int nSize, bool (*pComparison)(int, int));
 
bool Ascending(int nX, int nY)
{
    return nY > nX;
}
 
bool Descending(int nX, int nY)
{
    return nY < nX;
}
 
int main()
{
    vector<int> myVector = { 3, 7, 9, 5, 6, 1, 8, 2, 4 };
    SelectionSort(myVector, 9, Descending);
    SelectionSort(myVector, 9, Ascending);
    //SelectionSort(myVector,9) //Sorts Ascending by default
    return 0;
}

 void SelectionSort(vector<int> &anVector, int nSize, bool (*pComparison)(int, int))
{
    for (int nStartIndex= 0; nStartIndex < nSize; nStartIndex++)
    {
        int nBestIndex = nStartIndex;
        for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++)
        {
            if (pComparison(anVector[nCurrentIndex], anVector[nBestIndex])) 
                nBestIndex = nCurrentIndex;
        }
        swap(anVector[nStartIndex], anVector[nBestIndex]);
    }

    for (int iii=0; iii < nSize; iii++)
        cout << anVector[iii] << " ";
    cout << endl;
}
Last edited on
1
2
3
bool Ascending( int, int ) ; // declare it

void SelectionSort( int*,  int, bool (*)(int,int) = Ascending ) ; // use it 
thanks. I put the '=' after the bool. that's why it wasn't working for me XD
PS Trivia...

Better style?

1
2
    vector<int> myVector = { 3, 7, 9, 5, 6, 1, 8, 2, 4 };
    SelectionSort(myVector, myVector.size(), Descending); // rather than 9 


So now, if you add a few more numbers, you don't have to re-count!
Last edited on
Topic archived. No new replies allowed.