C++ 中 HashMap 用法

#include <iostream>
#include <unordered_map> // 引入unordered_map头文件
using namespace std;

int main() {
    // 创建一个unordered_map实例
    std::unordered_map<std::string, int> wordMap;

    // 向HashMap中插入数据
    wordMap["apple"] = 10;
    wordMap["banana"] = 20;
    wordMap["cherry"] = 30;

    // 通过key查找value
    int appleCount = wordMap["apple"];
    std::cout << "appleCount: " << appleCount << std::endl;

    // 遍历HashMap
    for (auto& pair : wordMap) {
        std::cout << pair.first.c_str() << " : " << pair.second << std::endl;
    }

    // 查询HashMap中是否含有某个key
    if (wordMap.find("apple") != wordMap.end()) {
        std::cout << "Found apple in the map." << std::endl;
    }
    else {
        std::cout << "Apple not found in the map." << std::endl;
    }

    // 删除HashMap中的元素
    wordMap.erase("banana");

    // 清空HashMap
    // wordMap.clear();

    return 0;
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C没有内置的HashMap数据结构,但可以使用一些技巧来实现类似的功能。一种常见的方法是使用哈希表(hash table)或关联数组(associative array)来模拟HashMap。 在C,你可以使用结构体和数组来创建自己的哈希表。下面是一个简单的示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 10 // 定义哈希节点结构体 typedef struct { char* key; int value; } HashNode; // 创建哈希表结构体 typedef struct { HashNode* nodes[SIZE]; } HashMap; // 哈希函数 int hashFunction(const char* key) { int sum = 0; for (int i = 0; i < strlen(key); i++) { sum += (int)key[i]; } return sum % SIZE; } // 初始化哈希表 void initHashMap(HashMap* hashMap) { for (int i = 0; i < SIZE; i++) { hashMap->nodes[i] = NULL; } } // 插入键值对到哈希表 void insert(HashMap* hashMap, const char* key, int value) { int index = hashFunction(key); HashNode* newNode = (HashNode*)malloc(sizeof(HashNode)); newNode->key = strdup(key); newNode->value = value; hashMap->nodes[index] = newNode; } // 根据键查找值 int get(HashMap* hashMap, const char* key) { int index = hashFunction(key); HashNode* node = hashMap->nodes[index]; if (node != NULL && strcmp(node->key, key) == 0) { return node->value; } return -1; // 找不到返回-1 } int main() { HashMap hashMap; initHashMap(&hashMap); insert(&hashMap, "apple", 5); insert(&hashMap, "banana", 3); insert(&hashMap, "orange", 7); printf("Value for 'apple': %d\n", get(&hashMap, "apple")); printf("Value for 'banana': %d\n", get(&hashMap, "banana")); printf("Value for 'orange': %d\n", get(&hashMap, "orange")); return 0; } ``` 这个示例使用了一个简单的哈希函数,将键转换为索引值,并使用该索引将节点存储在哈希表的相应位置。insert函数将给定的键值对插入哈希表,get函数根据键查找对应的值。 请注意,这只是一个简单的示例,实际的哈希表实现可能需要更多的功能和更复杂的哈希函数,以提高性能和处理冲突等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值