【问题标题】:Insert Pair as a key in map using c++使用 C++ 在地图中插入对作为键
【发布时间】:2018-06-28 05:55:19
【问题描述】:

我想知道如何使用 c++ 在地图中插入对,这是我的代码:

map< pair<int, string>, int> timeline;

我尝试使用以下方法插入它:

timeline.insert(pair<pair<int, string> , int>(make_pair(12, "str"), 33);
//and
timeline.insert(make_pair(12, "str"), 33);

但我得到了错误

\main.cpp|66|error: no matching function for call to 'std::map&lt;std::pair&lt;int, std::basic_string&lt;char&gt; &gt;, int&amp;&gt;::insert(std::pair&lt;int, const char*&gt;, int)'|

【问题讨论】:

  • 你应该发布(完整的)错误信息
  • @appleapple 我添加了它。

标签: c++ dictionary std-pair


【解决方案1】:

std::map::insert 期望 std::map::value_type 作为其参数,即std::pair&lt;const std::pair&lt;int, string&gt;, int&gt;。例如

timeline.insert(make_pair(make_pair(12, "str"), 33));

或更简单的

timeline.insert({{12, "str"}, 33});

如果你想就地构造元素,你也可以使用std::map::emplace,例如

timeline.emplace(make_pair(12, "str"), 33);

LIVE

【讨论】:

    【解决方案2】:

    如有疑问,请简化。

    auto key = std::make_pair(12, "str");
    auto value = 33;
    
    timeline.insert(std::make_pair(key, value));
    

    【讨论】:

      【解决方案3】:

      简单地使用传统方式:

      timeline[key] = value;
      

      对于插入和检索对:

       timeline[{1,"stackOverFlow"}] = 69;
         
         for(auto i: timeline)
              {
                  
                  cout<< i.first.first;
                  cout<< i.first.second;
                  cout<< i.second;
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-06
        • 1970-01-01
        • 2011-10-30
        • 2013-05-31
        相关资源
        最近更新 更多