分享

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

 dbn9981 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!

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多