C++-map:map判断key是否存在【myMap.find(item)!=myMap.end()】

当所查找的关键key出现时,它返回数据所在对象的位置,如果沒有,返回iter与end函数的值相同。

// find 返回迭代器指向当前查找元素的位置否则返回map::end()位置
iter = mapStudent.find("123");
 
if(iter != mapStudent.end())
       cout<<"Find, the value is"<<iter->second<<endl;
else
   cout<<"Do not Find"<<endl;

一、利用find

#include <unordered_map>

unordered_map<string, int> dist;

dist.find(x) != dist.end();//x元素存在
dist.find(x) == dist.end();//x元素不存在
// map::find
#include <iostream>
#include <map>
 
int main ()
{
  std::map<char,int> mymap;
  std::map<char,int>::iterator it;
 
  mymap['a']=50;
  mymap['b']=100;
  mymap['c']=150;
  mymap['d']=200;
 
  it = mymap.find('b');
  if (it != mymap.end())
    mymap.erase (it);
 
  // print content:
  std::cout << "elements in mymap:" << '\n';
  std::cout << "a => " << mymap.find('a')->second << '\n';
  std::cout << "c => " << mymap.find('c')->second << '\n';
  std::cout << "d => " << mymap.find('d')->second << '\n';
 
  return 0;
}
elements in mymap:
a => 50
c => 150
d => 200

二、利用count 

#include <unordered_map>
unordered_map<string, int> dist;
dist.count(x) == 1;//x元素存在
dist.count(x) == 0;//x元素不存在

三、利用迭代器遍历

#include <unordered_map>
unordered_map<string, int> dist;

unordered_map<string, int>::iterator it = dist.begin();
bool IsExist = false;
while(it != dist.end())
{
	if(it->first == x)
	{
		IsExist = true;
		break;
	}
	it++;
}	
IsExist == true;//x元素存在
IsExist == false;//x元素不存在

C++中map.find()函数_dutmathjc的博客-CSDN博客_map.find

C++(14):判断map中key值是否存在_Just_like_fire的博客-CSDN博客_判断map中key是否存在

C++ map用法总结(整理)_sevencheng798的博客-CSDN博客_c++ map

C++中如何查询map中是否存在某个元素_YMWM_的博客-CSDN博客_c++ map 查找存在某个值

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值