Insert a pair key in map

我只是一个虾纸丫 提交于 2021-01-07 02:49:35

问题


The way to insert a pair in a map is that:

std::map<char,int> mymap;

  // first insert function version (single parameter):
  mymap.insert ( std::pair<char,int>('a',100) );

but now I'm trying to insert this in a map:

map<pair<int,int>, int> map1; //(pair is the key and int is a value)

I tried this:

pair<int,int> p;
p.first = 5;
p.second = 20;

map1.insert(pair<int,int>,double> (p,0));

So, how I can do it?


回答1:


There are so many possibilities for this. You may choose any of the below which suits you better.

  1. Using make_pair

map<pair<int,int>, int> m; m.insert(make_pair(make_pair(5,20, 0));

  1. Using curly braces

map<pair<int,int>, int> m; m.insert({{5,20}, 0});

  1. Declaring a C++ Pair first

pair<int,int> p(5,20); map<pair<int,int>, int> m; m.insert(make_pair(p, 0));




回答2:


You can define and fill pairs manually if you want, but it's more common and idiomatic to use make_pair, or (since C++17) the deduction guides for pair:

map1.insert(std::make_pair(std::make_pair(5,20),0));

map1.insert(std::pair{std::pair{5,20},0}); // C++17 or later



回答3:


First, if you are constructing the key while inserting, you may want to use emplace instead, since it will construct the key and value in place and is also better equipped to forward the arguments passed to it without explicit construction. So your first example would be simplified to

mymap.emplace('a', 100);

while your second example will surely work as

map1.emplace(std::piecewise_construct, std::forward_as_tuple(5, 20), std::forward_as_tuple(0));

and from C++17 onwards may also work as

map1.emplace(5, 20, 0);

See for examples here and here



来源:https://stackoverflow.com/questions/59303840/insert-a-pair-key-in-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!