设置类忽略定义的 comp fn 和默认比较中的错误

set class ignoring defined comp fn and errors on default comparison

本文关键字:默认 比较 错误 fn comp 定义 设置      更新时间:2023-10-16

>我正在使用与 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
};

一些研究:

  • 类库
  • 同一类的问题 - 建议使用 STL Set 类,在这种情况下,我可能仍然需要帮助了解如何定义比较函数,因此发布问题
我有 19 个 C2784 错误,

都与某种形式的"错误 C2784:'bool std::operator ==(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &(' 有关:无法从"词典::更正T"中推断出"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 的比较函数必须是严格弱排序,因此该类与 STL set不同。

该错误指示正在使用默认OperatorCmp,我不知道为什么,但是您可以通过为CorrectionT类型定义operator<operator==来使默认起作用。