Effective STL学习笔记-条款24
来源:互联网 发布:js时间格式化插件 编辑:程序博客网 时间:2024/06/06 23:51
当关乎效率时应该在map::operator[]和map-insert之间仔细选择
假设有一个支持默认构造函数和赋值构造函数的类:
class Widget{public: Widget() {} Widget(int) {} const Widget& operator=(int) {}}; map<int, Widget> map; map[0] = 0; map[1] = 1; map[2] = 2;
书上说,这种情况下使用operator[]操作的map,会先创建一个Widget临时变量,随后析构这个临时变量,最后进行一个赋值操作。
实际上根据我的测试,个人认为临时变量以已经被移动构造优化了。
在map操作最重要的应该是,key是否存在,然后进行所需要的操作,这里给出一个简单的判断key存在的示例:
//每个map必须的key值都需要在这里声明enum class MapParam{ Apple, Lemon, Peach};using paramMap = map<MapParam, string>;//判断是否存在某个key 这个key取值于MapParamtemplate<typename Key>bool isExistParam(paramMap thisMap, Key key){ return thisMap.find(key) != thisMap.end();}//获取某个key下的valuetemplate<typename ReturnType, typename Key>ReturnType getParam(paramMap thisMap, Key key){ auto constIter = thisMap.find(key); if (constIter == thisMap.end()) { //throw } return constIter->second;} paramMap thisMap; thisMap.insert(make_pair<MapParam, string>(MapParam::Apple, "Apple")); thisMap.insert(make_pair<MapParam, string>(MapParam::Lemon, "Lemon")); if (isExistParam(thisMap, MapParam::Apple)) { cout << getParam<std::string>(thisMap, MapParam::Apple) << endl; } if (isExistParam(thisMap, MapParam::Lemon)) { cout << getParam<std::string>(thisMap, MapParam::Lemon) << endl; } if (isExistParam(thisMap, MapParam::Peach)) { cout << getParam<std::string>(thisMap, MapParam::Peach) << endl; }
这个map没有peach这个key所以打印:
AppleLemon
阅读全文
0 0
- Effective STL学习笔记-条款24
- 【Effective STL】条款1-5学习笔记
- 【Effective STL】条款6-12学习笔记
- 【Effective STL】条款13-18学习笔记
- Effective STL学习笔记-条款1
- Effective STL学习笔记-条款7
- Effective STL学习笔记-条款8-9
- Effective STL学习笔记-条款13|14
- Effective STL学习笔记-条款19
- Effective STL学习笔记-条款20
- Effective STL学习笔记-条款21
- Effective STL学习笔记-条款23
- Effective STL学习笔记-条款30
- Effective STL学习笔记-条款31
- Effective STL学习笔记-条款32
- Effective STL学习笔记-条款33
- Effective STL学习笔记-条款34
- Effective STL学习笔记-条款36
- python 笔记
- http://nian.so/#网站的拓展工具编写
- git学习1
- iOS 数据结构~链表图
- Learning Python Part I 之 字典
- Effective STL学习笔记-条款24
- leetcode 538. Convert BST to Greater Tree
- synchronized锁的重入问题
- 洛谷P1842奶牛玩杂技 解题报告
- Linux-4.9.2内核在mini2440上的移植(十五)——总结
- Codeforces 813D Two Melodies(维护转移来源的DP)
- 顺序表与链表操作
- Anaconda conda 32位python2.7与64位python3+共存 常见命令
- Java随机生成6位数字