Std :: sort using an inherited functor

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()); // {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;
}
+5
source share
1 answer

You must use it std::ref(), otherwise the argument will be passed by value (causing an attempt to copy-build an object of a type BaseSortthat is illegal because it BaseSortis abstract - and even if it weren’t, you would get a cut):

sort(values.begin(), values.end(), std::ref(*sortStrategy));
//                                 ^^^^^^^^
+9
source

All Articles