至于为什么 emplace()、emplace_hint() 执行效率会比 insert() 方法高,可阅读《为什么emplace()、emplace_hint()执行效率比insert()高》一文,虽然此文的讲解对象为 map 容器,但就这 3 个方法来说,unordered_map 容器和 map 容器是一样的。
template <class... Args>
pair<iterator, bool> emplace ( Args&&... args );
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main() { //创建 umap 容器 unordered_map<string, string> umap; //定义一个接受 emplace() 方法的 pair 类型变量 pair<unordered_map<string, string>::iterator, bool> ret; //调用 emplace() 方法 ret = umap.emplace("STL教程", "http://c.biancheng.net/stl/"); //输出 ret 中包含的 2 个元素的值 cout << "bool =" << ret.second << endl; cout << "iter ->" << ret.first->first << " " << ret.first->second << endl; return 0; }程序执行结果为:
bool =1
iter ->STL教程 http://c.biancheng.net/stl/
template <class... Args>
iterator emplace_hint ( const_iterator position, Args&&... args );
举个例子:可以这样理解,emplace_hint() 方法中传入的迭代器,仅是给 unordered_map 容器提供一个建议,并不一定会被容器采纳。
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main() { //创建 umap 容器 unordered_map<string, string> umap; //定义一个接受 emplace_hint() 方法的迭代器 unordered_map<string,string>::iterator iter; //调用 empalce_hint() 方法 iter = umap.emplace_hint(umap.begin(),"STL教程", "http://c.biancheng.net/stl/"); //输出 emplace_hint() 返回迭代器 iter 指向的键值对的内容 cout << "iter ->" << iter->first << " " << iter->second << endl; return 0; }程序执行结果为:
iter ->STL教程 http://c.biancheng.net/stl/
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有