在c ++中使用枚举作为数组索引

时间:2015-03-05 22:46:22

标签: c++ enums

#include <stdlib.h>
#include <stdio.h>
using namespace std;



void main(){
    char *resolutions[] = { "720x480", "1024x600", "1280x720", "1920x1080" };

    int x = 0;

    enum ResMode
    {
        p480,
        p600,
        p720,
        p1080
    }; 
    ResMode res = p480;

    printf("\nPlease enter the resolution you wish to use now by entering a number");
    printf("\n480p[0], 600p[1], 720p[2], 1080p[3]");
    gets(res);

    printf("\nThe resolution you have selected is %s", resolutions[res]);

}

所以基本上我希望能够按1并让它从枚举中选择p600并将其作为1024x600放在下一行。我收到类型转换错误。 我该如何解决这个问题?

4 个答案:

答案 0 :(得分:6)

您希望将某些项目关联与其他项目相关联。通常在查找表或映射中描述关联。

std::map<ResMode, std::string> map_table =
{
  {p480,     string("720x480")},
  {p600,     string("1024x600")},
  {p720,     string("1280x720")},
  {p1080,    string("1920x1080")},
};

int main(void)
{
  cout << map_table[p480] << "\n";
  return EXIT_SUCCESS;
}

同样,您可以菜单选项映射到枚举。

修改1

std::map<unsigned int, ResMode> selection_map =
{
  {0, p480}, {1, p600}, {2, p720}, {3, p1080},
};

int main(void)
{
  cout << "\n"
       << "Please enter the resolution you wish to use now by entering a number\n"
       <<"480p[0], 600p[1], 720p[2], 1080p[3]";
  unsigned int selection = 0;
  cin >> selection;
  if (selection < 4)
  {
    Resmode resolution_index = selection_map[selection];
    cout << "You chose: "
         << map_table[resolution_index]
         << "\n";
  }
  return EXIT_SUCCESS;
}

答案 1 :(得分:2)

int不能隐式转换为enum。您必须阅读int然后自己投射。例如,

int resInt;
scanf("%d", &resInt);
res = static_cast<ResMode>(resInt);//Note that this does not do bound checking.

答案 2 :(得分:2)

您可以使用&#34; scanf&#34;而不是&#34;得到&#34;,像这样:

scanf("%d",&res); // I recommend use scanf_s

或者带有std :: cin的iostream库。但在接受输入后,请务必检查输入是否正确。

答案 3 :(得分:-1)

正如otehrs指出的那样,没有直接的方法可以做到这一点。但是,您可以使用一些配方/技巧。我修改了你的代码如下:

#include <stdlib.h>
#include <stdio.h>


#define SOME_ENUM(DO) \
    DO(_720x480)  \
    DO(_1024x600) \
    DO(_1280x720) \
    DO(_1920x1080)

#define MAKE_ENUM(VAR) VAR,
enum class RESOLUTIONS
{
    SOME_ENUM(MAKE_ENUM)
};

#define MAKE_STRINGS(VAR) #VAR,
const char* const
RESOLUTION_NAMES[] =
{
    SOME_ENUM(MAKE_STRINGS)
};



const char *
GET_RESOLUTION_NAME(RESOLUTIONS type)
{
    return RESOLUTION_NAMES[static_cast<int>(type)];
}

int
GET_RESOLUTION_VALUE(RESOLUTIONS type)
{
    return static_cast<int>(type);
}

RESOLUTIONS
GET_RESOLUTION(int i)
{
    return static_cast<RESOLUTIONS>(i);
}



using namespace std;



int main(){


    printf("\nPlease enter the resolution you wish to use now by entering a number");

    printf("\n480p[0], 600p[1], 720p[2], 1080p[3]");

    int res_type;

    cin >> res_type;


    RESOLUTIONS selected_res = GET_RESOLUTION(res_type);

    printf("\nThe resolution you have selected is %s\n\n", GET_RESOLUTION_NAME(selected_res));

    return 0;

}

很抱歉没有提供解释,因为我现在必须走了。可以找到此食谱here。该代码适用于c ++ 11。