Bor*_*lov 5 c++ pointers std c++11
我想使用不同的策略来对矢量进行排序.但我无法弄清楚如何传递子仿函数并在std::sort以后使用它.每当我使用抽象类进行排序策略时,我最终都会cannot allocate an object of abstract type出错.有没有办法使用继承的仿函数作为std::sort参数?谢谢!
#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;
}
Run Code Online (Sandbox Code Playgroud)
你必须使用std::ref(),否则参数将通过值传递(导致尝试复制构造一个类型的对象BaseSort,这是非法的,因为它BaseSort是抽象的 - 即使它不是,你会得到切片):
sort(values.begin(), values.end(), std::ref(*sortStrategy));
// ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
831 次 |
| 最近记录: |