[C/C++标准库]_[初级]_[std::map的使用细节]
来源:互联网 发布:域名和空间要一起买吗 编辑:程序博客网 时间:2024/05/16 17:00
map
1.判断key是否存在的注意细节.
以前是通过[key]的返回值来判断key是否存在,这样是不行,因为map会创建不存在key的相应的pair.正确的方法是通过find来判断.
#include <map>#include <iostream>#include <stdlib.h>#include <string>#include <assert.h>#include <stdio.h>#include <typeinfo>using namespace std;int main(int argc, char const *argv[]){int i = 10;map<int,int*> m1;map<int,int> m2;map<int,string> m3;m1[i] = &i;m2[i] = i;m3[i] = string("test");cout << m1[i] << endl;cout << m2[i] << endl;cout << m3[i] << endl;//1.判断key是否存在的办法.assert(m1.find(3) == m1.end());assert(m2.find(3) == m2.end());map<int,string>::iterator res = m3.find(3);//注意:假如这里引用了m3[3],默认会创建这个key的一个空值.//对于不存在的key,通过[]引用这个key,默认会创建一个这个key的对应的value的初始值,//如果是指针类型就是NULL,类类型就是调用类的默认构造函数创建的默认值,//如果是数值类型,那么就会是0.如果调用了一次[key(不存在的key)],那么find的end()比较就会失败。// assert(m3[3].empty()); assert(m3.find(3) == m3.end()); //1.判断key是否存在的方法.return 0;}
输出:
0x22fedc10test
20140609:增加对map的枚举(key)排序功能
map的枚举是根据key的顺序进行枚举的.
代码:
#include <stdio.h>#include <stdint.h>#include <time.h>#include <algorithm>#include <iostream>#include <functional>#include <map>#include <string>using namespace std;int main(int argc, char const *argv[]){//1.添加std::map在枚举时的排序功能//1.默认顺序std::less<int>std::map<int,int> cache;cache[4] = 4;cache[1] = 1;cache[2] = 2;cache[5] = 5;std::map<int,int>::iterator it = cache.begin();cout << "less(default) order." << endl;for (; it != cache.end();++it){cout << (*it).first << endl;}//2.使用greatercout << "greater order." << endl;std::map<int,int,std::greater<int> > cache2(cache.begin(),cache.end());std::map<int,int>::iterator it2 = cache2.begin();for (; it2 != cache2.end();++it2){cout << (*it2).first << endl;}return 0;}
输出:
less(default) order.1245greater order.5421
1 1
- [C/C++标准库]_[初级]_[std::map的使用细节]
- [C/C++标准库]_[初级]_[自定义std::map的key]
- [C/C++标准库]_[初级]_[使用std::sort排序各种类型数据]
- [C/C++标准库]_[初级]_[std::vector的删除元素]
- [C/C++标准库]_[初级]_[如何实现std::string自己的Format(sprintf)函数]
- [C/C++标准库]_[初级]_[std::vector的多线程读写问题]
- [C++/object c]_[初级]_[std::map容器的使用总结和NSDictionary词典使用总结]
- [C/C++标准库]_[初级]_[std::deque和std::vector比较]
- [C/C++]_[初级]_[标准字符串std::string 所有函数的用法总结]
- [C/C++标准库]_[初级]_[map的查找函数分析]
- [C/C++标准库]_[初级]_[使用string stream]
- [C/C++标准库]_[初级]_[实用类std::pair]
- [C/C++标准库]_[初级]_[函数对象functor的使用]
- [C/C++标准库]_[初级]_[优先队列priority_queue的使用]
- [C/C++11]_[初级]_[使用std::tuple元组-固定大小的集合]
- [C/C++标准库]_[初级]_[使用freopen重定向标准输出]
- [C/C++标准库]_[初级]_[使用时间库]
- [C/C++标准库]_[初级]_[signal信号浅析]
- Ubuntu下常用命令集锦
- java相关环境变量配置
- LeetCode Valid Parentheses
- 中文传值解决乱码问题
- Android学习笔记(五一):服务Service(上)- IntentService
- [C/C++标准库]_[初级]_[std::map的使用细节]
- C++ 异或运算
- Git 常用命令详解
- 史上最全系列之Android开发基础之AsyncTask
- 找工作遇到挫折
- LeetCode :: 1.Balanced Binary Tree [树类题目分析]
- Android Bundle类
- 嵌入式linux开发基础知识整理
- 对话框程序, 在 OnInitDialog的最后 showWindow(SW_HIDE),不管用的原因