[英]why does std::map take a pair?
That syntax of: 该语法为:
std::map<int, int> m;
m.insert(std::make_pair(1, 42));
seems a bit crazy. 似乎有点疯狂。
Why is there no alternative insert(K k, V v)
method which would provide a much saner: 为什么没有替代的
insert(K k, V v)
方法可以提供更好的效果:
std::map<int, int> m;
m.insert(1, 42);
Yes, I'm aware of m[1] = 42
, but it has its own problems (creating an extra copy of the value object). 是的,我知道
m[1] = 42
,但是它有它自己的问题(创建值对象的额外副本)。
I can't tell you why that construct isn't allowed. 我不能告诉你为什么不允许这种构造。 Perhaps to keep
insert
similar to other containers' insert
method. 也许保持
insert
类似于其他容器的insert
方法。 However, since c++11, there is map::emplace that does what you want. 但是,自c ++ 11起,有map :: emplace可以满足您的需求。
std::map<int, int> m;
m.emplace(1, 42);
m.insert(x, y);
forces a copy of the two parameters; 强制复制两个参数; whereas
m.insert(std::make_pair(1, 42));
而
m.insert(std::make_pair(1, 42));
allows the call to get a const& pair
which avoids all copying. 允许调用获取一个
const& pair
,从而避免所有复制。 That way, map
can contain uncopyable objects (or heavy-duty copy objects) 这样,
map
可以包含不可复制的对象(或重型复制对象)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.