在枚举向量中找到

时间:2014-10-21 11:57:34

标签: c++ vector enums

我试图在向量中找到一个枚举项,好像有些==运算符问题。请问任何指导?

这是枚举

enum RESPONSE{
 GAME_START='P',
 GAME_HELP='H',
 GAME_QUIT='Q'
}

以下是用法

std::string s = getinputChar(); //this returns a string with a one character.

std::vector<RESPONSE> responces;
responces.push_back(GAME_START);
responces.push_back(GAME_QUIT);

std::vector<RESPONSE>::iterator it = find (responces.begin(), responces.end(), s.c_str());

错误:

error C2678: binary '==' : no operator found which takes a left-hand operand of type 'RESPONSE' (or there is no acceptable conversion)

3 个答案:

答案 0 :(得分:1)

您可以接受他们的输入char而不是string

char s = getinputChar();

然后,您可以将find更改为

std::vector<RESPONSE>::iterator it = find (responces.begin(), responces.end(), static_cast<RESPONSE>(s));

答案 1 :(得分:1)

试试这个:

RESPONSE r = (RESPONSE) s[0]; // conversion from input string to RESPONSE
std::vector<RESPONSE>::iterator it = find (responces.begin(), responces.end(), r);

答案 2 :(得分:0)

c_str()会返回const char *,但您的向量包含枚举。你想比较第一个角色吗?试试find(responces.begin(), responces.end(), static_cast<RESPONSE>(s[0]))。如果添加值大于char

的枚举,则此操作将停止