这个错误:
error C2664: 'Set::Set(int (__cdecl *)(ElemType,ElemType))' : cannot convert parameter 1 from 'int (__cdecl *)(CorrectionT &,CorrectionT &)' to 'int (__cdecl *)(ElemType,ElemType)'
是将此比较函数作为基于 BST 的 SET 类的一部分实现的结果,
int compareCorr(struct CorrectionT &a, struct CorrectionT &b)
{
if (a.editDistance < b.editDistance) return -1;
else if (a.editDistance == b.editDistance) return 0;
else return 1;
}
类(class)集
Set(int (*cmpFn)(ElemType, ElemType) = OperatorCmp);
而Set中比较函数的使用是为了相加
template <typename ElemType>
void Set<ElemType>::add(ElemType element) {
bst.add(element);
}
并在bst类中添加 重述头文件
BST(int (*cmpFn)(ElemType one, ElemType two) = OperatorCmp);
和函数添加
template <typename ElemType>
bool BST<ElemType>::add(ElemType data) {
bool createdNewNode = false;
recAddNode(root, data, createdNewNode);
if (createdNewNode) timestamp++;
return createdNewNode;
}
template <typename ElemType>
bool BST<ElemType>::recAddNode(nodeT * & t, ElemType & data,
bool & createdNewNode) {
if (t == NULL) {
t = new nodeT;
t->data = data;
t->bf = BST_IN_BALANCE;
t->left = t->right = NULL;
createdNewNode = true;
numNodes++;
return true;
}
int sign = cmpFn(data, t->data);
if (sign == 0) {
t->data = data;
createdNewNode = false;
return false;
}
int bfDelta = 0;
if (sign < 0) {
if (recAddNode(t->left, data, createdNewNode)) {
bfDelta = -1; /* left subtree is higher */
}
} else {
if (recAddNode(t->right, data, createdNewNode)) {
bfDelta = +1; /* right subtree is higher */
}
}
updateBF(t, bfDelta);
return (bfDelta != 0 && t->bf != BST_IN_BALANCE);
}
知道这里发生了什么——比较函数有什么问题吗?
最佳答案
compareCorr
的类型是int(Lexicon::CorrectionT&, Lexicon::CorrectionT &)
。其参数为引用。
构造函数的参数cmpFn
的类型是int(*)(ElemType, ElemType)
。它的参数是对象(不是引用)。
类型必须匹配。假设 ElemType
是 Lexicon::CorrectionT
,您必须将函数指针类型更改为具有引用参数类型或将比较器类型更改为具有对象参数类型。 (如果你走引用路线,他们应该都使用 const 引用,因为比较器不应该改变对象。)
或者,您可以像 STL 一样,将比较器作为类型的一部分,允许使用任意函数对象进行比较。然后,比较器只需要具有与被比较对象的类型兼容的类型的参数(即,不需要完全匹配)。
关于c++ - bst 比较模板上的错误 C2664,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11404622/