📜  检查键是否存在于C++映射或unordered_map中(1)

📅  最后修改于: 2023-12-03 14:55:51.604000             🧑  作者: Mango

检查键是否存在于C++映射或unordered_map中

在 C++ 中,我们可以使用映射(map)或无序映射(unordered_map)存储键值对。如果我们需要在一个映射或无序映射中检查某个键是否存在,我们可以使用 count 方法。本文介绍如何在 C++ 中使用 count 方法检查键是否存在于映射或无序映射中。

在映射中检查键是否存在

下面的代码演示了如何在映射中检查一个键是否存在:

#include <map>
#include <iostream>

int main()
{
    std::map<std::string, int> my_map = {{"apple", 4}, {"banana", 2}, {"orange", 1}};

    if (my_map.count("apple"))
    {
        std::cout << "The key 'apple' exists in the map." << std::endl;
    }
    else
    {
        std::cout << "The key 'apple' does not exist in the map." << std::endl;
    }

    if (my_map.count("grape"))
    {
        std::cout << "The key 'grape' exists in the map." << std::endl;
    }
    else
    {
        std::cout << "The key 'grape' does not exist in the map." << std::endl;
    }

    return 0;
}

以上代码定义了一个映射,其中包含三个键值对。然后,我们使用 count 方法检查键 "apple""grape" 是否存在于映射中。运行代码,输出为:

The key 'apple' exists in the map.
The key 'grape' does not exist in the map.

可以看到,count 方法返回的是一个整数,如果键存在,则返回 1,否则返回 0。因此,我们可以在 if 语句中使用 count 方法进行条件判断。

在无序映射中检查键是否存在

无序映射的用法和映射类似,在使用 count 方法时也是一样的。下面的代码演示了如何在无序映射中检查一个键是否存在:

#include <unordered_map>
#include <iostream>

int main()
{
    std::unordered_map<std::string, int> my_map = {{"apple", 4}, {"banana", 2}, {"orange", 1}};

    if (my_map.count("apple"))
    {
        std::cout << "The key 'apple' exists in the unordered_map." << std::endl;
    }
    else
    {
        std::cout << "The key 'apple' does not exist in the unordered_map." << std::endl;
    }

    if (my_map.count("grape"))
    {
        std::cout << "The key 'grape' exists in the unordered_map." << std::endl;
    }
    else
    {
        std::cout << "The key 'grape' does not exist in the unordered_map." << std::endl;
    }

    return 0;
}

以上代码定义了一个无序映射,其中包含三个键值对。然后,我们使用 count 方法检查键 "apple""grape" 是否存在于无序映射中。运行代码,输出为:

The key 'apple' exists in the unordered_map.
The key 'grape' does not exist in the unordered_map.

和映射一样,无序映射的 count 方法也返回一个整数,如果键存在,则返回 1,否则返回 0。我们同样可以在 if 语句中使用 count 方法进行条件判断。

总结

在 C++ 中,我们可以使用映射或无序映射存储键值对,并使用 count 方法检查键是否存在。使用 count 方法很简单,只需要调用映射或无序映射对象的 count 方法,并将待查询的键作为参数传入即可。返回的整数是存在与否的真值,我们可以在 if 语句中根据需要进行处理。