1. map中访问了不存在的键值
先来看一下主函数的内容
map<char, int> test;
for (auto& p : test) cout << p.first << ' ' << p.second << endl;
if (test['c']) cout << "YES" << endl;
cout << "访问过后" << endl;
for (auto& p : test) cout << p.first << ' ' << p.second << endl;
输出的测试结果
可以看出这里并没有创建’c’的键值,但是这里在 if 判断中访问了键值’c’,‘c’ 并不存在,所以map的处理机制是创建新的键值对。
处理
为了避免出现这种情况,在进行查找时使用find函数或者是count函数
2.vector作为map的键值
代码测试和结果如下
//vector作为map的键值,不能作为unordered_map的键值
map<vector<int>, int> buffer;
vector<int> a = { 1,1 };
int c{ 2 };
cout << c << endl;
buffer[a]++;
vector<int> b = { 1,2 };
buffer[b]++;
for (map<vector<int>, int>::iterator p = buffer.begin(); p != buffer.end(); p++)
{
printf("(%d, %d) %d\n", p->first[0], p->first[1], p->second);
}
return 0;