[英]Why does std::map not have an insert function of type insert(key &k, val &v)
Why does std::map
not support an insert like the following: 为什么
std::map
不支持如下插入:
std::map<obj1, obj2> map_int;
void insert_map(obj1 &key, obj2 &val)
{
map_int.insert(key, val);
}
I know that the above is incorrect. 我知道上面的内容不正确。 I want to know what prevents from designing the insert function like that.
我想知道是什么阻止了这样设计插入函数。 It is more intuitive than creating a pair IMO.
它比创建一对IMO更直观。
In C++17, you can use: 在C ++ 17中,您可以使用:
map_int.try_emplace(key, val);
This actually returns some useful information: 这实际上返回一些有用的信息:
std::pair<std::map<obj1, obj2>::iterator, bool> p = map_int.try_emplace(key, val);
p.first
is an iterator that points to the element with the given key. p.first
是一个迭代器,它指向具有给定键的元素。 p.second
indicates whether the insertion took place. p.second
表示插入是否发生。 You can achieve a similar effect in C++11 with map_int.emplace(key, val)
, but there are some subtle differences (related to copying/moving of values). 您可以使用
map_int.emplace(key, val)
在C ++ 11中实现类似的效果,但是存在一些细微差别(与复制/移动值有关)。 Moreover, try_emplace
allows for convenient construction of arbitrary elements: 而且,
try_emplace
允许方便地构造任意元素:
struct X { X(int, char, bool); };
std::map<int, X> m;
m.try_emplace(10, 20, 'x', false); // constructs X(20, 'x', false) if new
A similar operation in C++11 would look like this: C ++ 11中的类似操作如下所示:
m.emplace(
std::piecewise_construct,
std::forward_as_tuple(10),
std::forward_as_tuple(20, 'x', false));
std::map
does have an insert()
method (several, in fact), it just has a different signature than what you are expecting. std::map
确实有一个insert()
方法(事实上有几个),它只有一个不同于你期望的签名。 You need to pass it a std::pair
containing the desired key and value, eg: 你需要传递一个包含所需键和值的
std::pair
,例如:
std::map<obj1, obj2> map_int;
void insert_map(obj1 &key, obj2 &val)
{
map_int.insert(std::make_pair(key, val));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.