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

用法:

		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的构造函数进行参数构造,导致消耗更多时间并产生更多垃圾数据,拉低性能

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值