用户在地图中选择项目

User selecting item in map

我目前正在编写一个命令行游戏程序,我将类别和解决方案存储在 map<string, vector<string>> 中。键值是类别,向量是解决方案字符串的向量。

我想提示用户 select 一个类别,但是我不确定最好的方法,因为我不想强迫用户手动输入类别,因此我只是用他们的 selection 接收一个整数。

有没有办法使用 int 访问地图? (例如 solutionMap[2] = 第二个值?)

这里是我的代码片段,只是为了澄清

cout << "\nCategories:\n-----------" << endl;
int categoryCount = 1;
for (map<string, vector<string> >::iterator it = solutionMap.begin(); it != solutionMap.end(); ++it){
    cout << categoryCount << ": " << it->first << endl;
    ++categoryCount;
}

// Prompt user for selection and save as currentCategory
int currentCategory;
bool isValid = false;

do{
    cout << "Please enter the number of the category you would like to use: ";
    cin >> currentCategory;

    // if cin worked and number is in range, continue out of the loop
    if (cin.good() && currentCategory <= solutionMap.size()){
        isValid = true;
    }
    else{
        cout << "Invalid entry!" << endl;

        // Clear the buffer
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
} while (!isValid);

此时我想做的是将数字发送到游戏 class 并且 select 使用 selected 键值从向量中随机解,但据我所知,我需要 selection 作为字符串才能找到它。

如有任何帮助,我们将不胜感激!

如果您想使用整数索引访问您的地图,您可以按以下步骤进行:

 auto ix=solutionMap.begin();   // bidirectional iterator to the map 
 advance (ix,currentCategory);  // move the iterator
 cout << "choice is "<<ix->second<<endl;      // here you are 

但要小心:一旦您 insert/remove 一个元素,元素的顺序可能不再与您显示的菜单相对应。

它是如何工作的?

地图的迭代器是双向的:一次只能前进或后退 1 个元素。 advance() 重复此操作正确的次数

备选方案

如果您不真正将地图用作关联数组,并且主要使用菜单和索引,则应选择另一种变体,使用向量而不是地图:

 vector<pair<string, vector<string>> solutionMap; 

然后您可以使用它们的索引轻松访问这些元素。如果偶尔需要使用键字符串查找特定元素,仍然可以使用 find_if()。