打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C++中如何查询map中是否存在某个元素
userphoto

2022.12.02 北京

关注
//1 利用count
#include <unordered_map>
unordered_map<string, int> dist;
dist.count(x) == 1;//x元素存在
dist.count(x) == 0;//x元素不存在
//2 利用find
dist.find(x) != dist.end();//x元素存在
dist.find(x) == dist.end();//x元素不存在
//3 利用迭代器遍历
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元素不存在

示例代码,

#include <iostream>
#include <unordered_map>

using namespace std;

void method1(unordered_map<string, int> dist, string x)
{
    if(dist.count(x) == 1)
        cout << "键值对dist中存在" << x << "!" << endl;
    else
        cout << "键值对dist中不存在" << x << "!" << endl;
}

void method2(unordered_map<string, int> dist, string x)
{
    if(dist.find(x) != dist.end())
        cout << "键值对dist中存在" << x << "!" << endl;
    else
        cout << "键值对dist中不存在" << x << "!" << endl;
}

void method3(unordered_map<string, int> dist, string x)
{
    unordered_map<string, int>::iterator it = dist.begin();
    bool IsExist = false;
    while(it != dist.end())
    {
        if(it->first == x)
        {
            IsExist = true;
            break;
        }
        it++;
    }
    if(IsExist)
       cout << "键值对dist中存在" << x << "!" << endl;
    else
       cout << "键值对dist中不存在" << x << "!" << endl;
}


int main()
{

    unordered_map<string, int> dist;
    dist["Chinese"] = 1;
    dist["math"] = 2;
    dist["English"] = 3;
    dist["physics"] = 4;
    dist["chemistry"] = 5;
    dist["biology"] = 6;

    //1 利用count
    cout << "1利用count: " << endl;
    method1(dist, "Chinese");
    method1(dist, "history");

    //2 利用find
    cout << "2利用find: " << endl;
    method2(dist, "Chinese");
    method2(dist, "history");

    //3 利用迭代器遍历
    cout << "3利用迭代器遍历: " << endl;
    method3(dist, "Chinese");
    method3(dist, "history");

    return 0;
}

输出为,

1利用count: 
键值对dist中存在Chinese!
键值对dist中不存在history!
2利用find: 
键值对dist中存在Chinese!
键值对dist中不存在history!
3利用迭代器遍历: 
键值对dist中存在Chinese!
键值对dist中不存在history!
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C++STL与泛型编程(3)容器之分类与测试
C++ unordered
《C++ Primer》笔记 第11章 关联容器
boost::unordered_map 和 std::map 的效率,内存比较
STL中的常用的vector,map,set,Sort用法 - c/c++程序设计 - j...
标准模板类(STL)(二),具体容器简介
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服