简体   繁体   English

为什么std :: map需要一对?

[英]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.

相关问题 为什么std :: map接受std :: pair作为键,但std :: unordered_map不接受? - Why does std::map accept a std::pair as key, but std::unordered_map does not? 为什么`std :: pair`将`std :: tuple`作为ctor参数类型而不是`const std :: tuple&`? - Why does `std::pair` take `std::tuple` as ctor argument type rather than `const std::tuple&`? 为什么std :: map :: insert不能使用键和值而不是std :: pair? - Why can't std::map::insert take a key and a value rather than an std::pair? 如何从 std::map 中的 std::pair 的 std::vector 获取输入? - How to take input from std::vector of std::pair in a std::map? 为什么C ++允许类型为std :: map而没有默认构造函数而不是std :: pair? - Why does C++ allow type has no-default constructor for std::map while not std::pair? 为什么std :: map :: const_iterator在std :: for_each期间调用std :: pair构造函数,但是一个简单的for循环却没有? - Why does std::map::const_iterator call the std::pair constructor during a std::for_each, but a simple for loop does not? map 是否将元素存储为 std::pair? - Does map store elements as std::pair? 为什么std :: make_pair不返回一对? 还是呢? - Why does std::make_pair not return a pair? Or does it? 比较两个map :: iterators:为什么需要std :: pair的拷贝构造函数? - Comparing two map::iterators: why does it need the copy constructor of std::pair? 为什么 std::pair 公开成员变量? - Why does std::pair expose member variables?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM