21xrx.com
2024-09-19 10:13:24 Thursday
登录
文章检索 我的文章 写文章
C++中的字典实现
2023-06-27 01:54:43 深夜i     --     --
C++ 字典 实现 数据结构 搜索算法

字典是一种用于存储和检索关键字的数据结构。在C++中,可以使用各种方式实现字典,例如数组、链表、哈希表等。以下是一些常见的方式。

数组实现字典

使用数组来实现字典相对简单,但是查询效率较低。主要思路是将每个关键字保存在数组中,并通过遍历数组来查找目标关键字。

int dict[100];

int key = 10;

for(int i=0; i<100; i++){

  if(dict[i] == key)

    cout << "the key is found at index " << i << endl;

    break;

}

链表实现字典

链表是一种动态数据结构,可以添加或删除元素而不需要移动其他元素。因此,用链表来实现字典可以提高效率。主要思路是将每个关键字和对应的值作为节点保存在链表中,在查找时从头开始遍历链表。

struct Node {

  int key;

  int value;

  Node* next;

};

Node* head = new Node;

head->key = 10;

head->value = 20;

head->next = NULL;

int key = 10;

Node* ptr = head;

while(ptr){

  if(ptr->key == key)

    cout << "the value of key " << key << " is " << ptr->value << endl;

    break;

  ptr = ptr->next;

}

哈希表实现字典

哈希表是一种使用哈希函数将关键字映射到位置的数据结构,因此查询效率非常高。主要思路是将每个关键字和对应的值保存在哈希表中,在查找时使用哈希函数计算关键字的位置,并在该位置查找目标关键字。

class HashTable {

  private:

    static const int tableSize = 100;

    struct Node {

      int key;

      int value;

      Node* next;

    };

    Node* hashTable[tableSize];

  public:

    HashTable();

    int hashFunction(int key);

    void addItem(int key, int value);

    int findValue(int key);

};

HashTable::HashTable(){

  for(int i=0; i

    hashTable[i] = new Node;

    hashTable[i]->key = 0;

    hashTable[i]->value = 0;

    hashTable[i]->next = NULL;

  }

}

int HashTable::hashFunction(int key)

  return key % tableSize;

void HashTable::addItem(int key, int value){

  int index = hashFunction(key);

  if(hashTable[index]->key == 0){

    hashTable[index]->key = key;

    hashTable[index]->value = value;

  } else {

    Node* ptr = hashTable[index];

    Node* newNode = new Node;

    newNode->key = key;

    newNode->value = value;

    newNode->next = NULL;

    while(ptr->next)

      ptr = ptr->next;

    ptr->next = newNode;

  }

}

int HashTable::findValue(int key){

  int index = hashFunction(key);

  Node* ptr = hashTable[index];

  while(ptr){

    if(ptr->key == key)

      return ptr->value;

    ptr = ptr->next;

  }

  return -1;

}

int main(){

  HashTable dict;

  dict.addItem(10, 20);

  dict.addItem(20, 30);

  int value1 = dict.findValue(10);

  int value2 = dict.findValue(20);

  cout << "the value of key 10 is " << value1 << endl;

  cout << "the value of key 20 is " << value2 << endl;

  return 0;

}

总结

以上是C++中实现字典的一些常见方法,其中哈希表是最常用的方法之一,因为它的查询效率高。在实际应用中,可以根据需求选择不同的方法来实现字典。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复