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&

本文介绍了C++中std::map的使用细节,特别是如何正确判断key是否存在,强调不能通过[key]操作来检查,而应使用find方法。另外,还提到了map的枚举功能,它会按照key的顺序进行枚举。
订阅专栏 解锁全文
283

被折叠的 条评论
为什么被折叠?



