I have a sorting function inside class Array and wanted to achieve something like in python sort(reverse=True)
. I want to show user that they can pass this parameter because right now arr.bubble_sort(true);
(check the code) dose not make much sense. I don't want lambda functions any idea how to achieve this.
Any other method also works because I know named parameters are not there in c++ probably.
PS: I have overloaded it by the way.
Regards,
// inside class Array
void bubble_sort(bool rev){ //overloaded bubble_sort
if(rev){
int i,j;
for(i=0; i<size-1; i++){
for(j=0; j<size-i-1; j++){
if(arr[j] < arr[j+1]){
std::swap(arr[j], arr[j+1]);
}
}
}
}
else{
int i,j;
for(i=0; i<size-1; i++){
for(j=0; j<size-i-1; j++){
if(arr[j] > arr[j+1]){
std::swap(arr[j], arr[j+1]);
}
}
}
}
}
int main()
{
int n;
std::cin >> n;
Array arr(n); // parameterized constructor initializing array of size n
arr.bubble_sort(true);
arr.print();
return 0;
}
Just provide this overloads:
void bubble_sort(std::function<bool<int, int>> cmp) {
...
if(cmp(arr[j], arr[j+1])){
std::swap(arr[j], arr[j+1]);
}
...
}
void bubble_sort(bool rev = false)
{
bubble_sort(rev ? std::greater<int>{} : std::less<int>{});
}
Note that in c++ is static typed language, so overloads can be distinguish by argument type.