我遇到与here,here或here相同的问题,除了我为参数和函数添加了const:
#include <unordered_map>
#include <functional>
namespace zzz {
struct identity_t {
static const int ID_SIZE = 5;
static const int LSB = 4; // = ID_SIZE - 1
unsigned char id[ID_SIZE];
inline bool operator< (const identity_t& rhs) const {
for (int i = 0; i < ID_SIZE; i++) if (id[i] != rhs.id[i]) return (id[i] < rhs.id[i]);
return false; // equal
}
unsigned char operator[] (const int& i) {return id[i];}
};
class hash_identity_t {
public:
long operator()(const identity_t& x) const {
return (long) x[identity_t::LSB];
}
};
class equal_to_identity_t {
public:
bool operator()(const identity_t& lhs, const identity_t& rhs) const {
for (int i = 0; i < identity_t::ID_SIZE; i++) if (lhs[i] != rhs[i]) return false;
return true;
}
};
但是我有相同的编译错误:
error: passing 'const zzz::identity_t' as 'this' argument of 'unsigned char zzz::identity_t::operator[](const int&)' discards qualifiers [-fpermissive]
答案 0 :(得分:4)
您尝试在const
函数identity_t::operator[]
中的const
参数上调用非const
函数(long hash_identity_t::operator( const identity_t& x )
)。
制作identity_t::operator[]
const
蚂蚁。
//--------------------------------------vvvvv
unsigned char operator[] (const int& i) const {return id[i];}
答案 1 :(得分:1)
使用 std::map 的 at()
方法。
const mapped_type & at (const key_type &__k) const