I would like to use different strategies to sort a vector. But I can't figure out how to pass a child functor and use it in std::sort
later on. Whenever I use abstract class for sorting strategy I end up with cannot allocate an object of abstract type
error. Is there a way to use inherited functors as std::sort
arguments? Thanks!
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class BaseSort{
public:
virtual ~BaseSort() {};
virtual bool operator()(const int& a, const int& b) = 0;
};
class Asc : public BaseSort{
public:
bool operator()(const int& a, const int& b){
return a < b;
}
};
class Desc : public BaseSort{
public:
bool operator()(const int& a, const int& b){
return a > b;
}
};
void print(const vector<int>& values) {
for (unsigned i = 0; i < values.size(); ++i) {
cout << values[i] << ' ';
}
cout << endl;
}
int main() {
vector<int> values = {2,1,3};
sort(values.begin(), values.end(), Asc()); // {1,2,3}
print(values);
sort(values.begin(), values.end(), Desc()); // {3,2,1}
print(values);
Asc* asc = new Asc();
sort(values.begin(), values.end(), *asc); // {1,2,3}
print(values);
BaseSort* sortStrategy = new Desc();
sort(values.begin(), values.end(), *sortStrategy); //cannot allocate an object of abstract type ‘BaseSort’
print(values);
return 0;
}
You have to use std::ref()
, otherwise the argument will be passed by value (causing an attempt to copy-construct an object of type BaseSort
, which is illegal since BaseSort
is abstract - and even if it were not, you would get slicing):
sort(values.begin(), values.end(), std::ref(*sortStrategy));
// ^^^^^^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With