如何给HashTable添加数据以及如何取得HashTable中的key和value的值

首先给HashTable添加数据
Hashtable ht  =   new  Hashtable();
ht.Add(
1 , " c " );
ht.Add(
2 , " b " );
ht.Add(
3 , " a " );
然后拿到一个HashTable如何遍历 取得key和value的值
 IDictionaryEnumerator myEnumerator  =  ht.GetEnumerator();
  
while  (myEnumerator.MoveNext())
 
{
     
object htkey =  myEnumerator.key;
     
object htValue = myEnumerator.Value;
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在C语言,哈希表(Hashtable)是一种常见的数据结构,用于快速存储和检索数据。它基于哈希函数将键(Key)映射到存储桶(Bucket),每个桶存储一个键对。下面是一个简单的哈希表的定义和使用场景: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define TABLE_SIZE 100 typedef struct { char* key; int value; } KeyValue; typedef struct { KeyValue* data[TABLE_SIZE]; } Hashtable; Hashtable* createHashtable() { Hashtable* hashtable = (Hashtable*)malloc(sizeof(Hashtable)); memset(hashtable->data, 0, sizeof(hashtable->data)); return hashtable; } unsigned int hash(const char* key) { unsigned int hashValue = 0; while (*key) { hashValue = (hashValue << 5) + *key++; } return hashValue % TABLE_SIZE; } void insert(Hashtable* hashtable, const char* key, int value) { unsigned int index = hash(key); KeyValue* keyValue = (KeyValue*)malloc(sizeof(KeyValue)); keyValue->key = strdup(key); keyValue->value = value; hashtable->data[index] = keyValue; } int find(Hashtable* hashtable, const char* key) { unsigned int index = hash(key); KeyValue* keyValue = hashtable->data[index]; if (keyValue && strcmp(keyValue->key, key) == 0) { return keyValue->value; } return -1; } void destroyHashtable(Hashtable* hashtable) { for (int i = 0; i < TABLE_SIZE; i++) { KeyValue* keyValue = hashtable->data[i]; if (keyValue) { free(keyValue->key); free(keyValue); } } free(hashtable); } int main() { Hashtable* hashtable = createHashtable(); // 插入键对 insert(hashtable, "apple", 5); insert(hashtable, "banana", 3); insert(hashtable, "orange", 7); // 查找 printf("The value of apple is: %d\n", find(hashtable, "apple")); printf("The value of banana is: %d\n", find(hashtable, "banana")); printf("The value of orange is: %d\n", find(hashtable, "orange")); destroyHashtable(hashtable); return 0; } ``` 这个示例代码实现了一个简单的哈希表,可以插入键对和查找对应的。通过`createHashtable`函数可以创建一个空的哈希表,通过`insert`函数可以插入一个键对,通过`find`函数可以查找对应键的,通过`destroyHashtable`函数可以销毁哈希表。 哈希表的使用场景包括: 1. 缓存:哈希表可以用于快速存储和检索缓存数据,提高访问速度。 2. 字典:哈希表可以用于实现字典,将键映射到对应的。 3. 数据索引:哈希表可以用于构建数据索引,根据键快速查找对应的数据。 4. 频率统计:哈希表可以用于统计数据的频率,记录某个元素出现的次数。 希望对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值