当前位置:   article > 正文

C++实现hash_set_c++ hash_set

c++ hash_set

头文件:

  1. #include<iostream>
  2. using namespace std;
  3. template<class hash_type>
  4. class hash_set
  5. {
  6. private:
  7. hash_type array[100000];
  8. int hash_fun(hash_type original);
  9. public:
  10. hash_set();//构造函数
  11. void insert(hash_type value);//插入一个元素
  12. void erase(hash_type target);//删除一个元素
  13. bool contain(hash_type query);//判断一个元素是否在集合中
  14. };
类函数实现:

  1. #include "hash_set.h"
  2. template<class hash_type>
  3. #define MAX_LENGTH 100000
  4. int hash_set<hash_type>::hash_fun(hash_type original)
  5. {
  6. return ((int)original) % MAX_LENGTH;
  7. }
  8. template<class hash_type>
  9. hash_set<hash_type>::hash_set()
  10. {
  11. for(int i = 0; i < MAX_LENGTH; i++)
  12. array[i] = NULL;
  13. }
  14. template<class hash_type>
  15. bool hash_set<hash_type>::contain(hash_type query)
  16. {
  17. int hash_value = hash_fun(query);
  18. while(array[hash_value] != NULL)
  19. {
  20. if(array[hash_value] == query)
  21. return true;
  22. hash_value++;
  23. if(hash_value >= MAX_LENGTH)
  24. hash_value = 0;
  25. }
  26. return false;
  27. }
  28. template<class hash_type>
  29. void hash_set<hash_type>::insert(hash_type value)
  30. {
  31. if(contain(value))
  32. {
  33. cout << "The value exists.\n";
  34. return;
  35. }
  36. int hash_value = hash_fun(value);
  37. while(array[hash_value] != NULL)
  38. {
  39. hash_value++;
  40. if(hash_value >= MAX_LENGTH)
  41. hash_value = 0;
  42. }
  43. array[hash_value] = value;
  44. }
  45. template<class hash_type>
  46. void hash_set<hash_type>::erase(hash_type target)
  47. {
  48. int hash_value = hash_fun(target);
  49. while(array[hash_value] != NULL)
  50. {
  51. if(array[hash_value] == target)
  52. break;
  53. hash_value++;
  54. if(hash_value >= MAX_LENGTH)
  55. hash_value = 0;
  56. }
  57. if(array[hash_value] == NULL)
  58. cout << "The value doesn't exist.\n";
  59. else
  60. array[hash_value] = NULL;
  61. }

测试main函数:

  1. #include<iostream>
  2. #include "hash_set.cpp"
  3. int main()
  4. {
  5. hash_set<int> hs;
  6. while(true)
  7. {
  8. cout << "Begin test:\ninput 1 to insert;2 to find; 3 to delete\n";
  9. int flag;
  10. int value;
  11. cin >> flag;
  12. switch (flag)
  13. {
  14. case 1:
  15. cout << "input the value to insert:\n";
  16. cin >> value;
  17. hs.insert(value);
  18. break;
  19. case 2:
  20. cout << "input the value to find:\n";
  21. cin >> value;
  22. if(hs.contain(value))
  23. cout << "Yes\n";
  24. else cout << "No\n";
  25. break;
  26. case 3:
  27. cout << "input the value to delete\n";
  28. cin >> value;
  29. hs.erase(value);
  30. break;
  31. default:
  32. cout << "Input error.\n";
  33. break;
  34. }
  35. }
  36. return 0;
  37. }



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/227394
推荐阅读
相关标签
  

闽ICP备14008679号