使用 c++ 在映射中插入对作为键

Insert Pair as a key in map using c++

本文关键字:插入 c++ 映射 使用      更新时间:2023-10-16

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

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)'|

std::map::insert期望std::map::value_type作为其参数,即 std::pair<const std::pair<int, string>, int> .例如

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

或更简单

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

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

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

如有疑问,请简化。

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

只需使用传统方式:

timeline[key] = value;

对于配对的输入和重新竞争:

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