在映射c++中,使用enum作为键来设置和获取值

Set and get value with enum as a key in map c++

本文关键字:设置 获取 c++ 映射 enum 使用      更新时间:2023-10-16

所以我想做的是将枚举映射到对象的指针。这是我当前的代码:

  enum state {A,B,C};
class imageTexture {
public:
    imageTexture(std::string path) {};
};
int main() {
    std::map<state, imageTexture*> theMap;
    theMap[A] = new imageTexture("a");
    return 0;
}

联机版本:http://ideone.com/v9HA4h

这是它停止工作的地方。完整错误为:

地图没有可行的过载操作员[]

我对此做了一些研究,发现了一些常数,但我可以很好地克服这个错误。我还浏览了一些地图的示例代码,并感到更加困惑:

std::map<string, int> theMap;
theMap['A'] = 1;

这和我所做的一样,但我的不起作用。有人能帮我吗?如有任何解释,不胜感激。

编辑:更新代码中我有问题的部分

编辑2:我在网上试过这个代码,它有效。然而,它不在我的笔记本电脑里。这只是我的编译器不能使用c++11的问题吗?

查看您的代码或帖子,我认为您缺少了一些重要的东西。这个代码工作得很完美:

#include <iostream>
#include <map>
enum state { RED, YELLOW, GREEN };
class foo
{
    int a;
};

int main()
{
    std::map<state, foo *> theMap;
    theMap[RED] = new foo();
    std::cout << "That's all" << std::endl;
}

实例

已编辑:它也适用于C++98(-std=C++98)