I would like to use different strategies to sort the vector. But I cannot figure out how to pass in a child functor and use it in std::sortlater. Whenever I use an abstract class for a sorting strategy, I end up with an error cannot allocate an object of abstract type. Is there a way to use inherited functors as arguments std::sort? Thank!
#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());
print(values);
sort(values.begin(), values.end(), Desc());
print(values);
Asc* asc = new Asc();
sort(values.begin(), values.end(), *asc);
print(values);
BaseSort* sortStrategy = new Desc();
sort(values.begin(), values.end(), *sortStrategy);
print(values);
return 0;
}
source
share