简体   繁体   English

为什么需要将对插入地图?

[英]Why pair is required to insert into map?

Though I do not dislike it, but find it inconvinient to declare a pair<X,Y> object, or make a call to make_pair , in order to call map::insert . 虽然我不喜欢它,但发现声明一pair<X,Y>对象或调用make_pair ,以便调用map::insertmake_pair Why insert doesn't take two arguments instead to specify Key and Value respectively. 为什么insert不使用两个参数来分别指定Key和Value。

While I understand it is for compatibility with other STL containers, that exhibit value_type . 虽然我理解它是为了与其他STL容器兼容,但它展示了value_type But find method takes key_type which breaks this compatibility assertion. 但是find方法采用key_type来破坏这种兼容性断言。 map has both key_type and mapped_type , so why cant map have: map既有key_type又有mapped_type ,所以为什么cant map有:

iterator insert(const key_type&, const mapped_type&);

Yes, there are overloads of insert taking iterator(s). 是的, insert迭代器有重载。 But this two-argument insert could have been mixed well. 但是这个两个参数insert可能混合得很好。

Just one advantage I see is: less call stack usage. 我看到的一个优点是:减少了调用堆栈的使用。

EDIT : Just found out that insert is the only method that takes value_type , that is pair<X,Y> . 编辑 :刚刚发现insert唯一采用value_type方法,即pair<X,Y> Many other methods like find , erase , at , count , equal_range , lower_bound , upper_bound and operator[] take key_type . 许多其他方法,如finderaseatcountequal_rangelower_boundupper_boundoperator[]采用key_type

All standard library containers define a value_type member type, and their interfaces generically operate in terms of this value_type : insert , push_back , push_front . 所有标准库容器都定义了一个value_type成员类型,它们的接口通常按照value_typeinsertpush_backpush_front The new interface emplace adds a way of constructing a value_type object as if by: 新的接口emplace添加了一种构造value_type对象的方法,就像通过:

value_type(std::forward<Args>(args)...)

Basically, there is no special interface provided for the satellite-data associative containers (ie maps) which is aware of the special structure of value_type (which is defined, not perfectly well-known, to be pair<const key_type, mapped_type> ), with the exception of find and erase and operator[] , which take key_type arguments. 基本上,没有为卫星数据关联容器(即地图)提供特殊的接口,这些容器知道value_type的特殊结构(已定义,不是完全众所周知的,是pair<const key_type, mapped_type> ),除了finderase以及key_type参数的operator[] key_type

It is perhaps an oversight of the standard, or perhaps it was never deemed to be a problem, since you can always use make_pair , make_tuple or forward_as_tuple , or emplace , to create map value types. 这也许是标准的监督,或许它从未被认为是一个问题,因为你可以随时使用make_pairmake_tupleforward_as_tuple ,或emplace ,创建映射值的类型。

(There is one problem with insert and move-only mapped types that has surfaced and is subject of this recent proposal .) insert和仅移动映射类型存在一个问题,它已浮出水面并且是最近提案的主题。)

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

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