我是靠谱客的博主 光亮吐司,这篇文章主要介绍insert,emplace,try_emplace,现在分享给大家,希望可以做个参考。

map,unordered_map的emplacetry_emplace方法,set,unordered_set的insert方法,其返回值为:pair<iterator, bool>

  1. 若插入成功(即原容器中没有相应元素(对于set一族)或相应key(对于map一族)),则iterator为指向插入元素的迭代器,bool为true,标志成功插入
  2. 若插入失败(容器中已有元素或key),则iterator指向已存在元素的迭代器,bool为false,标志插入失败

unorder_map和map中try_emplace的优势:

Unlike insert or emplace, these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as std::map<std::string, std::unique_ptr>. In addition, try_emplace treats the key and the arguments to the mapped_type separately, unlike emplace, which requires the arguments to construct a value_type (that is, a std::pair).
——https://en.cppreference.com/w/cpp/container/map/try_emplace

用法:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
std::map<int, std::string>test; test.insert(make_pair(1, str)); // (1) test.emplace(make_pair(1, str)); // (2) test.emplace(2, str); // (3) 也可写作test.emplace<int, std::string>(2, str); test.try_emplace(3, str); // (4)

简而言之,对于不发生插入的情况,(4)中try_emplace不会进行参数构造,即不会去调用std::pair的构造函数,而(3)中emplace无论插入成功或失败都会调用std::pair的构造函数进行参数构造,导致消耗更多时间并产生更多垃圾数据,拉低性能

最后

以上就是光亮吐司最近收集整理的关于insert,emplace,try_emplace的全部内容,更多相关insert内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部