有兩種方法,一種直接法,一種間接法
先看直接法,要用到map的find()方法
map<int, string> i2s_map; auto pos=i2s_map.find(k); flag= (pos==i2s_map.end())? 0:1;
flag=0,表示map中沒有要查找的key值
flag=1,表示map中存在查找的key值,且迭代器pos指向該key值
判斷某key是否存在也可以使用map的count方法來間接判定
count接受一個參數key值,返回map中key值為給定值的元素總數
1 map<int, string> i2s_map; 2 int mount = i2s_map.count(100);
如果mount=0,則map中不存在key值為100的元素,反之則存在