std :: map<>的自定义键 [英] Custom Key for std::map<>
问题描述
我正在尝试使用以下struct
作为std::map
的自定义键:
I am trying to use the following struct
as a custom key for std::map
:
struct ActionId {
// ENCAPSULATED MEMBERS
private:
size_t _id;
static size_t _root;
static size_t incrementedRoot() {
return (_root += 1);
}
// INTERFACE
public:
ActionId() :
_id(incrementedRoot()) { }
ActionId(const ActionId& that) :
_id(that._id) { }
ActionId& operator=(const ActionId& that) {
this->_id = that._id;
return *this;
}
bool operator==(const ActionId& that) const {
return this->_id == that._id;
}
bool operator!=(const ActionId& that) const {
return this->_id != that._id;
}
bool operator<(const ActionId& that) const {
return this->_id < that._id;
}
};
以下字典是单独的InputManager
类的成员:
The following dictionary is a member of a separate InputManager
class:
std::map<ActionId, std::set<sf::Keyboard::Key>> _keyBindings;
在该成员函数中访问的
:
which is accessed in this member function:
std::set<sf::Keyboard::Key> InputManager::keysBoundTo(ActionId action) const {
return _keyBindings[action];
}
不幸的是,该函数抛出此编译器错误:
Unfortunately, the function is throwing this compiler error:
错误C2678:二进制'[':未找到采用'
const std::map<Game2D::ActionId,std::set<sf::Keyboard::Key,std::less<_Kty>,std::allocator<_Kty>>,std::less<Game2D::ActionId>,std::allocator<std::pair<const Game2D::ActionId,_Ty>>>
'类型的左操作数(或没有可接受的转换)的运算符
error C2678: binary '[' : no operator found which takes a left-hand operand of type '
const std::map<Game2D::ActionId,std::set<sf::Keyboard::Key,std::less<_Kty>,std::allocator<_Kty>>,std::less<Game2D::ActionId>,std::allocator<std::pair<const Game2D::ActionId,_Ty>>>
' (or there is no acceptable conversion)
根据本文,具有const
资格的ActionId
的operator<()
成员应足以将其设置为自定义地图键,而本文说,我需要做的只是使ActionId
可复制和可分配.显然,我的结构同时满足这两个条件,那么为什么InputManager::keysBoundTo()
不能编译?
According to this article, the operator<()
member of ActionId
with const
qualification should be sufficient to make it a custom map key, while this article says that all I need is to make ActionId
copiable and assignable. Clearly, my struct meets both of these criteria, so why won't InputManager::keysBoundTo()
compile?
推荐答案
索引运算符("[]")是std :: map的非常量成员函数.而您已经清楚地表明keysBoundTo
是const成员.
The index operator (the "[]") is a non-const member function of std::map. Whereas, you have clearly indicated that keysBoundTo
is a const member.
将keysBoundTo
重写为
std::set<sf::Keyboard::Key> InputManager::keysBoundTo(ActionId action) const
{
auto it = keyBindigs_.find(action);
if ( it == keyBindings_.end() )
return std::set<sf::Keyboard::Key>();
else
return it->second;
}
请注意,我已将您的成员变量重命名为带有下划线.请勿在下划线前使用标识符.
Notice that I renamed your member variable to have a trailing underscore. Do not use identifiers with leading underscores.
这篇关于std :: map<>的自定义键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!