【发布时间】:2015-06-12 20:30:20
【问题描述】:
我目前正在编写一个命令行游戏程序,其中我将类别和解决方案存储在map<string, vector<string>> 中。键值为类别,向量为解串向量。
我想提示用户选择一个类别,但是我不确定最好的方法,因为我不想强迫用户手动输入类别,因此只收到一个 int 与他们的选择.
有没有办法使用 int 来访问地图? (例如 solutionMap[2] = 第二个值?)
这是我的代码中的一个 sn-p,只是为了澄清
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);
此时我想做的是将数字发送到游戏类并使用选定的键值从向量中选择一个随机解决方案,但是据我所知,我需要将选择作为字符串找到它。
任何帮助将不胜感激!
【问题讨论】:
-
我应该补充一点,我尝试使用迭代器并将它的值增加 given-1 但似乎也无法让它工作。虽然我可能尝试不正确
-
为什么需要地图?似乎创建一个具有类别名称和解决方案的结构向量可能会更好。
-
类别和解决方案来自 CSV 文件的 ifstream。即使 csv 文件发生更改,程序也必须能够存储此数据。我认为地图是存储这些信息的最佳方式。大部分时间仍在学习,因此获取这些信息并制作结构略高于我的能力/专业知识