简体   繁体   中英

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

So what I want to do is mapping my enum to a pointer to an object. This is my current code:

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

Online version : http://ideone.com/v9HA4h

This is the place where it stops working. The full error is:

no viable overloaded operator[] for map

I have done some research on this and I found something with constant but I could get through this error well. I have also looked through some example code for map and get more confused:

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

This is the same as what I have done but mine is not working. Can someone help me out? Any explanation would be appreciated.

Edit: Update the part of the code where I have the problem

Edit 2: I tried the code online and it works. However, it doesn't in my laptop. Would it just the problem of my compiler not working with c++11?

Review your code or your post, I think that your are missing something important. This code works perfect:

#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: It works with C++98 as well (-std=c++98)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM