[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
原创粉丝点击