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; }
输出:
0x22fedc 10 test
[C/C++标准库]_[std::map的使用细节],布布扣,bubuko.com
原文:http://blog.csdn.net/infoworld/article/details/21696929