C++ Map 注意事項
在map中,由key查找value時,首先要判斷map中是否包含key
見 C++ Map find函數和count函數
重點:
如果不檢查,直接返回map[key],可能會出現意想不到的行爲。如果map包含key,沒有問題,如果map不包含key,使用下標有一個危險的副作用,會在map中插入一個key的元素,value取默認值,返回value。也就是說,map[key]不可能返回null。
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> test;
test[1] = 10;
test[2] = 20;
cout << test.size() << endl;
if(test[3] > test[4]){
}
cout << test.size() << endl;
}
輸出: