Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

c++哈希表如何使用

  1. User

    c++哈希表如何使用

  2. Assistant

    C++中可以使用std::unordered_map来实现哈希表。下面是一个使用哈希表的例子:

    #include <iostream>
    #include <unordered_map>
    
    int main() {
        // 创建一个哈希表
        std::unordered_map<std::string, int> hashMap;
    
        // 添加元素到哈希表
        hashMap["apple"] = 1;
        hashMap["banana"] = 2;
        hashMap["orange"] = 3;
    
        // 访问哈希表中的元素
        std::cout << "The value of apple is: " << hashMap["apple"] << std::endl;
        std::cout << "The value of banana is: " << hashMap["banana"] << std::endl;
    
        // 检查哈希表中是否存在某个键
        if (hashMap.find("orange") != hashMap.end()) {
            std::cout << "The key orange exists in the hash map." << std::endl;
        }
    
        // 删除哈希表中的元素
        hashMap.erase("banana");
    
        // 遍历哈希表
        for (auto& pair : hashMap) {
            std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
        }
    
        return 0;
    }
    

    上面的例子创建了一个存储键为字符串、值为整数的哈希表。可以使用[]操作符来添加、访问和修改哈希表中的元素。可以使用find()方法来查找哈希表中是否存在某个键。可以使用erase()方法来删除哈希表中的元素。可以使用范围for循环来遍历整个哈希表。