0

我正在尝试学习 C++ 并尝试为类似以下结构的简单哈希表编写代码:

array[0][0] array[0][1] array[0][2]
key 1        value 1      value 2

array[1][0] array[1][1] 
key 2        value 3     

array[2][0] array[2][1] array[2][2]
key 3        value 4      value 5

表示动态数组的数组。现在,下面是我的代码:

#include<iostream>
#include<conio.h>

using namespace std;

 int ele [10] ;
 int** arrays = new int*[10] ;

class HashTable
{
   public:

    HashTable()
    {    
         for(int i = 0 ; i < 10 ; i++)
         ele[i] = - 1 ;     // element array stores the number of elements in column of each row
    }

    void put(int key, int value){
         if(ele[key] == -1){
         arrays[key] = new int[1];
         arrays[key][0] = value ;  // initialize 2nd dimention
         ele[key] = 0 ; 
         }
         else{
              int num = ele[key] ;
              int temp[num + 1] ;
              for(int i = 0 ; i < num ; i++)
              temp [i] = arrays[key][i] ;
              temp[num+1] = value ;
              arrays[key] = new int[num + 1] ;
              for(int i = 0 ; i < num+1 ; i++)       // take all the elements in an temporary array and store it back
              arrays[key][i] = temp [i] ;
              ele[key] = num + 1 ;
              }

         }

};

main()
{

HashTable object;

 object.put(0 , 100);
 object.put(1 , 200);
 object.put(3 , 300);
 object.put(3 , 3000);
 object.put(3 , 30000);
 object.put(5 , 500);
 object.put(5 , 5000);
 object.put(5 , 50000);
 object.put(5 , 50); 


for (int i = 0 ; i < 10 ; i++ ){
int j = ele[i] ;

cout << j << " K ";

if(j != -1){
for (int k = -1 ; k < j ; k++ )    // print the values of corresponding keys
cout << arrays[i][k] << "  ";
}
}


 getch();
   return 0;
}

它使用 put 方法将值放入自定义 HashTable。

任何人都可以帮助我为什么上面的代码在尝试检索相应键的值时给出错误的输出值。

4

1 回答 1

2

这是行不通的:

for (int k = -1 ; k < j ; k++ )
    cout << arrays[i][k] << "  ";

您不能有带有负索引的数组。当你进入循环时,你有k = -1所以你尝试访问arrays[i][-1],这是行不通的。

其他建议:

  • 对象arraysele应该是你的类的成员,并在其中声明(作为私有成员)
  • On the line where you write arrays[key] = new int[num + 1], you forget to call delete on the previous object. This will cause a memory leak.
  • You should print your arrays using a method inside your function (like the put method) and then just call it using object.print() (if you named it print)
  • Testing if(j != -1) before the loop for (int k = -1; k < j; k++) is redundant: if j == -1 you will never go into the loop anyway.
于 2012-11-08T13:50:05.010 回答