c++ - std::map<> 的自定义键

标签 c++ struct key stdmap

<分区>

我正在尝试使用以下 struct作为 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的成员类:

std::map<ActionId, std::set<sf::Keyboard::Key>> _keyBindings;

在此成员函数中访问:

std::set<sf::Keyboard::Key> InputManager::keysBoundTo(ActionId action) const {
    return _keyBindings[action];
}

不幸的是,该函数抛出此编译器错误:

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)

根据 this article , operator<() ActionId的成员与 const资格应该足以使其成为自定义 map 键,而 this article说我只需要制作 ActionId可复制和可分配。显然,我的结构符合这两个标准,那么为什么不 InputManager::keysBoundTo()编译?

最佳答案

索引运算符(“[]”)是 std::map 的非常量成员函数。鉴于您已经明确指出 keysBoundTo 是一个 const 成员。

重写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;
}

请注意,我将您的成员变量重命名为具有尾随下划线。不要使用带有前导下划线的标识符。

关于c++ - std::map<> 的自定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31839913/

相关文章:

Python - 基于键/值标识的分组/合并字典

java - java中有什么方法可以阻止Control-Alt-Delete吗?

powershell - 使用powershell获取注册表项中特定字符串值的值

c++ - 对 C++ 的 std::wstring、UTF-16、UTF-8 以及在 Windows GUI 中显示字符串感到困惑

将指向较大结构的指针转换为指向较小结构的指针

c# - PInvoke 结构/函数中的奇怪错误

c - 搜索链表中的某个节点

c# - native C++ 和 C# 互操作

c# - 将参数从托管代码传递到非托管代码

c++ - Code::Blocks 正确找到但未能打开标准包括