map,unordered_map的emplace、try_emplace方法,set,unordered_set的insert方法,其返回值为:pair<iterator, bool>:
- 若插入成功(即原容器中没有相应元素(对于set一族)或相应key(对于map一族)),则iterator为指向插入元素的迭代器,bool为true,标志成功插入
- 若插入失败(容器中已有元素或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
12std::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内容请搜索靠谱客的其他文章。
发表评论 取消回复