多映射中的运算符函数错误

Error in operator function in multimap

本文关键字:函数 错误 运算符 映射      更新时间:2023-10-16

我正在尝试使用多键结构作为键创建多映射,但出现如下描述的错误:

法典:

struct stCont
{
    long long Tok;
    char Reserved;
    long long Asset;
}
struct MultiKey {
    char InstrumentName[6];
    char Symbol[10];
    long long ExpiryDate;
}
struct myComp
    {
       bool operator() (const MultiKey& lhs, const MultiKey& rhs)
       {
           if((lhs.ExpiryDate==rhs.ExpiryDate)&&(memcmp(lhs.InstrumentName,rhs.InstrumentName,6))&&(memcmp(lhs.Symbol,rhs.Symbol,10)))
           {
               return 1;
           }
           return 0;
       }
    };
std::multimap<MultiKey, stCont,myComp> cont_map;

错误:

expression having type 'const myComp' would lose some const-volatile qualifiers in order to call 'bool myComp::operator ()(const MultiKey &,const MultiKey &)'

你应该像这样重写多映射代码并删除 mycomp 结构:

struct MultiKey {
    char InstrumentName[6];
    char Symbol[10];
    long long ExpiryDate;

    bool operator< (const MultiKey& lhs)const
    {
        if((lhs.ExpiryDate==ExpiryDate)&&(memcmp(lhs.InstrumentName,InstrumentName,6))&&(memcmp(lhs.Symbol,Symbol,10)))
                   {
                       return true;
                   }
                   return false;
    }

};

你为什么不直接写operator < MultiKey? 或者你将不得不改变myComp因为它无论如何都不是multimap想要的(它想要一个小于比较的)。

查看 C++11 标准、§23.4.5.1和标题:

template <class Key, class T, class Compare = less<Key>,
    class Allocator = allocator<pair<const Key, T> > >
class multimap {
public:
    // ...
    class value_compare {
        friend class multimap;
    protected:
        Compare comp;
        value_compare(Compare c) : comp(c) { }
    public:
        typedef bool result_type;
        typedef value_type first_argument_type;
        typedef value_type second_argument_type;
        bool operator()(const value_type& x, const value_type& y) const {
            return comp(x.first, y.first);
        }
    };
    // ...
};

class value_compare定义的比较函数const。现在,我可能误解了标准,但如果operator()在类Compare中不const,这个定义似乎是无效的。

至于为什么它对某些人有用...也许关于实例化规则的一些细节可以防止这成为错误,或者不需要实现严格遵守标准中的类型定义;如果是这样,如果更精通标准的人可以澄清,我会很高兴。

若要修复编译错误,请将比较函数声明为 const 成员:

bool operator() (const MultiKey& lhs, const MultiKey& rhs) const
                                                           ^^^^^

然后你还有另一个问题:比较器需要执行"小于"比较,但你的比较器会进行相等比较。你想要类似的东西

if (lhs.ExpiryDate < rhs.ExpiryDate) return true;
if (lhs.ExpiryDate > rhs.ExpiryDate) return false;
if (memcmp(lhs.InstrumentName,rhs.InstrumentName,6) < 0) return true;
if (memcmp(lhs.InstrumentName,rhs.InstrumentName,6) > 0) return false;
if (memcmp(lhs.SymbolName,rhs.SymbolName,10) < 0) return true;
return false;

您可能会发现重载operator<比定义命名比较器类型更方便,这样就可以将std::multimap<MultiKey, stCont>与默认比较器一起使用。