【发布时间】:2013-10-25 05:47:39
【问题描述】:
如果您在以下函数中注意到它们都有相同的用于搜索整数位置的 for 循环。 Pop() 编译但我得到一个错误,因为 top() 与 const 限定符有关。堆类继承自 eecs281heap,它存储了一个函子 Comp 比较,其中 Comp 是类型名。讲师告诉我们访问函子的唯一方法是通过 this->() 所以我只是在这里寻找一些指导。谢谢
错误:将“const large”作为“bool large::operator()(int, int)”的“this”参数传递会丢弃限定符
在 int main 中运行以下命令后会发生这种情况。通过测试我已经知道构造函数可以正常工作。
vector <int> data={10,2,13};
poorman_heap<int,larger> y(data.begin(),data.end());
template<typename TYPE, typename COMP>
void poorman_heap<TYPE, COMP>::pop() {
int location=0;
for(int i=1;i<data.size();i++){
if(this->compare(data.at(i),data.at(location))){
location=i;
}
}
data.erase(data.begin()+location);
return;
}
template<typename TYPE, typename COMP>
const TYPE& poorman_heap<TYPE, COMP>::top() const {
int location=0;
for(int i=1;i<data.size();i++){
if(this->compare(data.at(i),data.at(location))){
location=i;
}
}
return data.at(location);
}
附:更大的是
struct greater{
bool operator()(int x,int y){
return x>y;
}
}
【问题讨论】:
-
难道
compare不是const? -
我认为是这样,但我不允许更改任何类编译,所以当我传入更大的仿函数进行比较时,我不知道如何使用 top( )
-
这没有多大意义。你是说
this->compare是greater实例吗?如果是这样,则您的代码已损坏,因为它假定TYPE是int。但是您可以即时创建一个本地greater实例,允许您在其上调用非常量方法。 -
我的构造函数初始化了一个通过 this->compare 访问的仿函数,我传递的大于 to。在其他方法中使用它时,它可以正常工作并适当排序。请记住,任何函子都可以传递到类中进行存储,但在这种情况下,我选择了更大的。如果这更有意义的话,我只是无法在 top() 类中访问这个函子