你能教我两者吗?
std::unordered_map::insert(const value_type&)
Run Code Online (Sandbox Code Playgroud)
和
template<class P> std::unordered_map::insert(P&&)
Run Code Online (Sandbox Code Playgroud)
存在于标准中?
我认为这insert(P&&)可以作为insert(const value_type&).
这两个都是重载
auto std::unordered_map::insert(const value_type&) -> ...
template<class P>
auto std::unordered_map::insert(P&&) -> ...
Run Code Online (Sandbox Code Playgroud)
有自己的优势,也不能完全取代对方.第一个似乎是第二个的特例,因为P可能会被推断出来const value_type&.关于第二次重载的好处是你可以避免不必要的副本.例如,在这种情况下:
mymap.insert(make_pair(7,"seven"));
Run Code Online (Sandbox Code Playgroud)
这里,make_pair的结果实际上是一个pair<int, const char*>而value_type不是pair<const int, string>.因此,我们不是创建临时value_type对象并将其复制到容器中,而是value_type通过转换参数和/或移动其成员来直接将对象创建到地图中.
另一方面,如果这样做也会很好:
mymap.insert({7,"seven"});
Run Code Online (Sandbox Code Playgroud)
但这个清单实际上不是表达!因此,编译器无法推断出第二次重载的P. 第一个重载仍然可行,因为您可以pair<const int,string>使用这样的列表复制初始化参数.
| 归档时间: |
|
| 查看次数: |
1608 次 |
| 最近记录: |