使用c ++在地图中插入对作为键

时间:2018-01-19 03:02:11

标签: c++ dictionary std-pair

我想知道如何使用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<std::pair<int, std::basic_string<char> >, int&>::insert(std::pair<int, const char*>, int)'|

3 个答案:

答案 0 :(得分:3)

std::map::insert期望一个std::map::value_type作为其参数,即std::pair<const std::pair<int, string>, int>。 e.g。

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

答案 1 :(得分:3)

如有疑问,请简化。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="content">CONDENSE THIS TEXT</span>

答案 2 :(得分:1)

只需使用传统方式:

timeline[key] = value;

对于配对的插入和检索:

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