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

rus*_*jen 3 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]);

}
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*ews 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;
}
Run Code Online (Sandbox Code Playgroud)

同样,您可以菜单选择映射到枚举.

编辑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;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么选择downvote?如果这些贬低者会发表评论,那将是件好事. (3认同)