gpt4 book ai didi

c++ - std::sort 使用继承的仿函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:22 25 4
gpt4 key购买 nike

我想使用不同的策略对 vector 进行排序。但我不知道如何传递子仿函数并稍后在 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;
}

最佳答案

你必须使用 std::ref() ,否则参数将按值传递(导致尝试复制构造 BaseSort 类型的对象,这是非法的,因为 BaseSort 是抽象的 - 即使它是不,你会得到切片):

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

关于c++ - std::sort 使用继承的仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15605834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com