我正在尝试使用多键结构作为键创建一个multimap,并得到了下面描述的一个错误:
代码:
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 &)'发布于 2013-09-06 11:30:26
您应该像这样重写multimap代码并删除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;
}
};发布于 2013-09-06 10:55:33
你为什么不直接为operator <写MultiKey呢?否则,您将不得不更改myComp,因为它并不是multimap想要的(它想要的比比较少)。
发布于 2013-09-06 11:12:48
查看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,这个定义似乎是无效的。
为什么它对某些人有效..。也许关于实例化规则的一些更精细的观点可以防止这成为一个错误,或者实现不需要严格遵守标准中的类型定义;如果是这样的话,我很高兴有人能够澄清更熟悉标准的人。
https://stackoverflow.com/questions/18655966
复制相似问题