简体   繁体   English

为什么std :: map :: insert不能使用键和值而不是std :: pair?

[英]Why can't std::map::insert take a key and a value rather than an std::pair?

std::map has the member function std :: map具有成员函数

template <class P> pair<iterator,bool> insert (P&& val);

which we use eg like so: 我们使用例如这样:

my_map.insert(std::make_pair(k, v));

Question is, why isn't there a variant of insert() which just takes a key and a value, ie 问题是,为什么没有insert()的变体,该变体只接受一个键和一个值,即

pair<iterator,bool> insert (K&& key, V&& value);

(with K and V being the template parameters of the map of course) which we would use eg like so: (当然,K和V是地图的模板参数),我们将这样使用:

my_map.insert(k, v);

That seems to me perfectly reasonable to have. 在我看来,这完全合理。

This was added in C++11 with the emplace members for all containers, which for map has the signature 它是在C ++ 11中添加的,其中emplace成员用于所有容器,而map具有签名

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );

If you're looking for a more obvious syntax, you can perform the same insertion using the key and values as separate entities like this: 如果您正在寻找更明显的语法,则可以使用键和值作为单独的实体执行相同的插入,如下所示:

my_map[k] = v;

Granted, this is two separate operations. 当然,这是两个单独的操作。 An insert followed by an assignment so it may not be as efficient as a single insert. 插入后跟分配,因此效率可能不如单个插入。 But then again, maps store store their entries as pairs so a call to an insert(k, v) function would probably wind up creating a pair<k, v> anyway. 但是话又说回来,地图存储将它们的条目存储为对,因此无论如何pair<k, v> insert(k, v)函数的调用可能最终会创建pair<k, v>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM