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

标签 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 输出。我收到类型转换错误。 我该如何解决这个问题?

最佳答案

看起来您想将一些项目关联到其他项目。通常关联在查找表或映射中进行描述。

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

关于c++ - 在 C++ 中使用枚举作为数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28889298/

相关文章:

java - 针对 Java 整数常量扩展提出适当的设计建议

java - 使用 gson 在 java 中初始化枚举

C++ 枚举类型未正确初始化

c++ - 为什么我得到不同的时间值

c++ - 详尽(暴力)算法改进

c# - 如何在 NHibernate 中使用枚举?

c - #defined 位标志和枚举 - 在 "c"中和平共处

c++ - 如何检测磁盘已满错误并让程序在获得可用磁盘空间后恢复

c++ - 使用 set_difference 时出现编译错误

c++ - 这是在 Qt 信号和槽中调用带有参数的函数的好方法吗