问题
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.
- Using make_pair
map<pair<int,int>, int> m;
m.insert(make_pair(make_pair(5,20, 0));
- Using curly braces
map<pair<int,int>, int> m;
m.insert({{5,20}, 0});
- 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 pair
s 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