【问题标题】:set class ignoring defined comp fn and errors on default comparison设置类忽略定义的comp fn和默认比较错误
【发布时间】:2012-07-08 09:14:58
【问题描述】:

我用的是自定义的Set类,和STL 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 错误都与某种形式的“错误 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

【问题讨论】:

    标签: c++ visual-studio-2008 set


    【解决方案1】:

    STL set 的比较函数必须是 Strict Weak Ordering,因此该类与 STL set 相同。

    错误表明正在使用默认的OperatorCmp,我不知道为什么,但是您可以通过为您的CorrectionT 类型定义operator&lt;operator== 来使默认的一个工作。

    【讨论】:

    • 我试过了,它导致设置类中的错误 - 我会再试一次
    • 严格的弱排序不是仅仅因为存在a == b的可能性吗?
    • 1) 我可以使用 STL 集吗?而且,我尝试将默认比较函数定义更改为 CorrectionT。但是,#include "lexicon.h" //template int OperatorCmp(Lexicon::CorrectionT one, Lexicon::CorrectionT two) { if (one.editDistance == two.editDistance) return 0; if (one.editDistance
    • 1) 我可以使用 STL 集吗?而且,我尝试将默认比较函数定义更改为 CorrectionT。有一些我无法解决的错误:C2653:'Lexicon':不是类或命名空间名称,C2065:'CorrectionT':未声明的标识符,C2146:语法错误:在标识符'one'之前缺少')'
    • 严格的弱排序返回真或假,而不是-1、0或+1,这是非常不同的。如果您为您的类型定义小于比较,则可以使用std::set。其他错误不相关,您只需要学习如何解释错误并自己修复它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多