本文介绍了我可以使用总是emplace替换插入单元素插入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在将单个元素插入到插入中时始终使用 emplace STL容器,像set,unordered_set?



从签名中, emplace 更简单,不涉及重载。是否有任何问题停止使用插入并使用 emplace 所有时间?



注意:有些问题询问 emplace 插入 / push_back 等(例如, a href =http://stackoverflow.com/questions/17893000/when-to-use-emplace-and-when-to-use-push-insert>此处和)我明白的区别,它似乎在我 emplace 在各方面都更好。我只想确认是否可以弃用 insert

解决方案

有一些示例可以适应 emplace 插入,显示行为可能不同。 / p>

这些例子可能看起来有点人为的,所以我会给一个希望看起来不那么如此的东西:

  #include< set> 

template< typename T>
T id(T x){return x; }

int main(){
std :: set< int(*)(int)> s;
s.insert(id); // OK
s.emplace(id); // error
s.emplace(id< int>); // OK
}

insert 可以推导出 id 的模板参数,因为它知道它想要什么类型。对于 emplace ,您会收到错误,除非您明确指定。


I was wondering if it is OK to always use emplace to replace insert when inserting a single element into a STL container, like set, unordered_set?

From the signature, emplace is simpler and do not involve overloads. Is there any issue with stop using insert and use emplace all the time?

Note: there are SO questions asking about the difference between emplace and insert/push_back etc. (e.g. here, here, and here) I understand the difference, and it seems to me that emplace is better in every way. I just want to confirm if it's OK to deprecate insert.

解决方案

There are some examples here that can be adapted to emplace and insert, showing when the behaviour may differ.

These examples may seem a bit artificial, so I'll give one that will hopefully appear less so:

#include <set>

template <typename T>
T id(T x) { return x; }

int main() {
    std::set<int(*)(int)> s;
    s.insert(id);       // OK
    s.emplace(id);      // error
    s.emplace(id<int>); // OK
}

insert can deduce the template parameter of id because it knows what type it wants. For emplace you get an error unless you explicitly specify.

这篇关于我可以使用总是emplace替换插入单元素插入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 05:59