大佬教程收集整理的这篇文章主要介绍了C++ map(STL map)operator[]和insert()效率对比(深度剖析),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <iostream> #include <map> //map #include <String> //String using namespace std; int main() { std::map<String,String> mymap; //借用 operator[] 添加新键值对 mymap["STL教程"] = "http://c.biancheng.net/java/"; cout << "old mymap:" << mymap["STL教程"] << endl; //借用 operator[] 更新某个键对应的值 mymap["STL教程"] = "http://c.biancheng.net/stl/"; cout << "new mymap:" << mymap["STL教程"] << endl; //借用insert()添加新键值对 std::pair<String,String> STL = { "Java教程","http://c.biancheng.net/python/" }; std::pair<std::map<String,String>::iterator,bool> ret; ret = mymap.insert(STL); cout << "old ret.iter = <{" << ret.first->first << "," << ret.first->second << "}," << ret.second << ">" << endl; //借用 insert() 更新键值对 mymap.insert(STL).first->second = "http://c.biancheng.net/java/"; cout << "new ret.iter = <" << ret.first->first << "," << ret.first->second << ">" << endl; return 0; }程序执行结果为:
old mymap:http://c.biancheng.net/java/
new mymap:http://c.biancheng.net/stl/
old ret.iter = <{Java教程,http://c.biancheng.net/python/},1>
new ret.iter = <Java教程,http://c.biancheng.net/java/>
mymap["STL教程"] = "http://c.biancheng.net/java/";此行代码中,mymap["STL教程"] 实际上是 mymap.operator[ ](“STL教程”) 的缩写(底层调用的 operator[ ] 方法),该方法会返回一个指向 “STL教程” 对应的 value 值的引用。
typedef map<String,String> mstr; //创建要添加的默认键值对元素 pair<mstr::iterator,bool>res = mymap.insert(mstr::value_type("STL教程",String())); //将新键值对的值赋值为指定的值 res.first->second = "http://c.biancheng.net/java/";可以看到,使用 operator[ ] 添加新键值对元素的流程是,先构造一个有默认值的键值对,然后再为其 value 赋值。
mymap.insert(mstr::value_type("STL教程","http://c.biancheng.net/java/"));此行代码和上面程序的执行效果完全相同,但它省略了创建临时 String 对象的过程以及析构该对象的过程,同时还省略了调用 String 类重载的赋值运算符。由于可见,同样是完成向 map 容器添加新键值对,insert() 方法比 operator[ ] 的执行效率更高。
//operator[] mymap["STL教程"] = "http://c.biancheng.net/stl/"; //insert() std::pair<String,"http://c.biancheng.net/python/" }; mymap.insert(STL).first->second = "http://c.biancheng.net/java/";仅仅从语法形式本身来考虑,或许已经促使很多读者选择 operator[ ] 了。接下来,我们再从执行效率的角度对比以上 2 种实现方式。
以上是大佬教程为你收集整理的C++ map(STL map)operator[]和insert()效率对比(深度剖析)全部内容,希望文章能够帮你解决C++ map(STL map)operator[]和insert()效率对比(深度剖析)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。