我使用的是与 STL Set 类基本相同的自定义 Set 类
问题是我以某种方式错误地实现了它并且使用了默认比较函数而不是我定义的比较。
Set<Lexicon::CorrectionT> Lexicon::suggestCorrections(Lexicon::MatchesT & matchSet)
{
Set<CorrectionT> suggest(compareCorr); //ordered Set
suggestCorrectionsHelper(root, suggest, 0, matchSet.testWord, 0, matchSet.testTime);
return suggest;
}
int compareCorr(Lexicon::CorrectionT a, Lexicon::CorrectionT b)
{
if (a.editDistance < b.editDistance)
return -1;
else if (a.editDistance == b.editDistance)
return 0;
else
return 1;
}
struct CorrectionT {
int editDistance; //stackItems
string suggestedWord; //stackItems
};
一些研究:
- The class library
- the same class 的问题- 建议使用 STL Set 类,在这种情况下,我可能仍需要帮助来理解如何定义比较函数,所以发布问题
我有 19 个 C2784 错误都与某种形式的“error C2784: 'bool std::operator ==(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' 相关:可能不从“Lexicon::CorrectionT”中推断出“const std::_Tree<_Traits> &”的模板参数
并引用此代码
template <typename Type>
int OperatorCmp(Type one, Type two) {
if (one == two) return 0;
if (one < two) return -1;
return 1;
}
我的问题:您建议如何纠正这个问题?
尝试更改默认定义类型:
#include "lexicon.h"
//template <typename Type>
int OperatorCmp(Lexicon::CorrectionT one, Lexicon::CorrectionT two) {
if (one.editDistance == two.editDistance) return 0;
if (one.editDistance < two.editDistance) return -1;
return 1;
}
#endif
最佳答案
STL 的比较函数 set
必须是 Strict Weak Ordering ,因此该类不与STL相同set
.
错误提示默认OperatorCmp
正在被使用,我不知道为什么,但是你可以通过定义 operator<
来使默认的工作。和 operator==
为你的CorrectionT
类型。
关于c++ - 设置类忽略定义的 comp fn 和默认比较错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387155/