typedef map <int, string> MAP_INT_STRING;
MAP_INT_STRING mapIntToString;
mapIntToString.insert (MAP_INT_STRING::value_type (3, “Three”));
我只找到了通过源代码将值插入到地图中的示例。我想知道如何允许用户在程序运行时这样做。我想这会涉及某种for循环,但我不确定如何设置它。
答案 0 :(得分:3)
int main() {
using namespace std;
map<int, string> m;
cout << "Enter a number and a word: ";
int n;
string s;
if (!(cin >> n >> s)) {
cout << "Input error.\n";
}
else {
m[n] = s;
// Or: m.insert(make_pair(n, s));
}
return 0;
}
答案 1 :(得分:2)
现在,认真地说。首先,您需要从用户获取值,然后将它们插入到地图中。像这样的东西:
std::map<int, std::string> m;
while (true) {
std::cout << "please give me an int\n";
int i;
std::cin >> i;
std::cout << "now gimme some string\n";
std::string s;
std::cin >> s;
m.insert(std::make_pair(i, s));
std::cout << "continue? (y/n)";
char c;
std::cin >> c;
if (c != 'y')
break;
}