首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >multimap中算子函数的错误

multimap中算子函数的错误
EN

Stack Overflow用户
提问于 2013-09-06 10:47:45
回答 4查看 183关注 0票数 1

我正在尝试使用多键结构作为键创建一个multimap,并得到了下面描述的一个错误:

代码:

代码语言:javascript
复制
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;

错误:

代码语言:javascript
复制
expression having type 'const myComp' would lose some const-volatile qualifiers in order to call 'bool myComp::operator ()(const MultiKey &,const MultiKey &)'
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-09-06 11:30:26

您应该像这样重写multimap代码并删除mycomp结构:

代码语言:javascript
复制
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;
    }


};
票数 1
EN

Stack Overflow用户

发布于 2013-09-06 10:55:33

你为什么不直接为operator <MultiKey呢?否则,您将不得不更改myComp,因为它并不是multimap想要的(它想要的比比较少)。

票数 1
EN

Stack Overflow用户

发布于 2013-09-06 11:12:48

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

代码语言:javascript
复制
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,这个定义似乎是无效的。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18655966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档