Inserting values into a map
typedef map <int, string> MAP_INT_STRING;
MAP_INT_STRING mapIntToString;
mapIntToString.insert (MAP_INT_STRING::value_type (3, “Three”));
I have only found examples where the values are inserted into the map through the source code. I would like to know how to allow a user do so as the 开发者_运维技巧program is running. I image this would involve some sort of for loop, but I am not certain how to set it up.
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;
}
now, speaking seriously. first you need to take values from users and then to insert them into your map. something like this:
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;
}
精彩评论