使用枚举作为map c ++中的键来设置和获取值

时间:2015-11-11 11:39:37

标签: c++ dictionary enums

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

  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的问题吗?

1 个答案:

答案 0 :(得分:1)

检查您的代码或帖子,我认为您遗漏了重要的内容。这段代码非常完美:

#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;
}

Live example

EDITED:它也适用于C ++ 98(-std = c ++ 98)

相关问题