简体   繁体   English

将值插入地图

[英]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. 我想象这会涉及某种for循环,但是我不确定如何设置它。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM