1. map[key]
通過鍵直接查找,如果存在就返回對應的值,如果不存在則返回0
map<char, int>map1;
map1['a'] = 1;
map1['b'] = 2;
cout << map1['a'] << endl; // 返回1
cout << map1['c'] << endl; // 返回0
2. map.find(key)
返回key對應的迭代器,如果不存在則返回map.end(),時間復雜度為O(logN)
if (map1.find('d') == map1.end())
cout << "NOT FONUND" << endl;
cout << map1.find('a')->second << endl; // 輸出1
3. map.count(key)
如果key存在就返回1,如果不存在則返回0。
cout << "map.count():" << endl;
cout << map1.count('b') << endl; // 返回1
cout << map1.count('d') << endl; // 返回0
完整測試代碼:
#include<bits/stdc++.h>
using namespace std;
int main() {
map<char, int>map1;
map1['a'] = 1;
map1['b'] = 2;
cout << map1['a'] << endl; // 返回1
cout << map1['c'] << endl; // 返回0
cout << "map.find():" << endl;
if (map1.find('d') == map1.end())
cout << "NOT FONUND" << endl;
cout << map1.find('a')->second << endl; // 輸出1
cout << "map.count():" << endl;
cout << map1.count('b') << endl; // 返回1
cout << map1.count('d') << endl; // 返回0
return 1;
}
發(fā)現(xiàn)一個有趣的問題:
輸出一個不存在的key的map映射值時,會把這個值存到map1里面,0為對應的value。
cout<<map[不存在的key];文章來源:http://www.zghlxwxcb.cn/news/detail-505705.html
#include<bits/stdc++.h>
using namespace std;
int main() {
map<char, int>map1;
map1['a'] = 1;
map1['b'] = 2;
cout << map1['a'] << endl; // 返回1
cout << map1['c'] << endl; // 這里相當于存入了['c',0]到map1中
cout << "map.find():" << endl;
if (map1.find('c') == map1.end())
cout << "NOT FONUND" << endl;
cout << map1.find('c')->second << endl; // 返回0
cout << "map.count():" << endl;
cout << map1.count('b') << endl; // 返回1
cout << map1.count('c') << endl; // 'c'存在所以返回1
return 1;
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-505705.html
到了這里,關(guān)于C++中map查找元素是否存在的3種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!