c++ - 将值插入 map

标签 c++

  typedef map <int, string> MAP_INT_STRING;

  MAP_INT_STRING mapIntToString;
  mapIntToString.insert (MAP_INT_STRING::value_type (3, “Three”));

我只找到了通过源代码将值插入 map 的示例。我想知道如何在程序运行时允许用户这样做。我想象这会涉及某种 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;
}

关于c++ - 将值插入 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987845/

相关文章:

c++ - QPushButton 不遵守水平扩展尺寸策略

c++ - 为什么要检查 Base 是 Derived 的私有(private)基还是 protected 基?

c++ - xutility(2227) : warning C4996: 'std::_Copy_impl'

c++ - 打破严格的别名并活着讲述它?

c++ - GLEW 未初始化;抛出 "Missing OpenGL Version"

c++ - 正在将未初始化的变量传递给另一个函数 UB

c++ - 如何在C++中将整数转换为其数字数组

c# - native dll 的 .net 包装器 - 如何将运行时错误的风险降至最低?

c++ - 解释了一种将 double 舍入为 32 位整数的快速方法

c++ - 多重继承中的构造函数调用顺序