[英]std::sort using inherited functor
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. 但我无法弄清楚如何传递子仿函数并在稍后使用它在
std::sort
中。 Whenever I use abstract class for sorting strategy I end up with cannot allocate an object of abstract type
error. 每当我使用抽象类进行排序策略时,我最终
cannot allocate an object of abstract type
错误cannot allocate an object of abstract type
。 Is there a way to use inherited functors as std::sort
arguments? 有没有办法使用继承的仿函数作为
std::sort
参数? 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 ): 你必须使用
std::ref()
,否则参数将通过值传递(导致尝试复制构造BaseSort
类型的对象,这是非法的,因为BaseSort
是抽象的 - 即使它不是,你会得到切片 ):
sort(values.begin(), values.end(), std::ref(*sortStrategy));
// ^^^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.