2016-11-21 5 views
0

ここでHashTableをコーディングしようとしています。私はかなり多くの関数をコーディングしており、プログラムはメインとコンパイルしています。何らかの理由で私の機能を見つけるのは、私が持っているメインと一緒に走るのが永遠に続くからです。また、コピーコンストラクタとoperator =のテストがクラッシュしています。以下、これを行うにはOKであるいかなる状況はありません、ハッシュテーブルfind関数のC++ HashTableの問題

structure 
{ 
    struct Record 
    { 
     TYPE data_; 
     string key_; 
     Record* Next ; 

     Record(const string& key, const TYPE& data) 
     { 
      key_ = key; 
      data_ = data; 
     } 
     Record() 
     { 
      key_ = "" ; 
      Next = nullptr; 
     } 



    }; 
    int TableSize ; 
    Record** records ; 


    template <class TYPE> 
    bool HashTable<TYPE>::find(const string& key, TYPE& value) 
    { 
     // int index = std::hash<TYPE> {}(value)%TableSize ; 
     int index = std::hash<string> {}(key)%TableSize ; 
     Record* temp = records[index] ; 
     while(temp != nullptr) 
     { 
      if(temp->data_ == value && temp->key_ == key) 
       return true ; 
      temp = temp->Next ; 
     } 
     return false ; 
    } 

operator= 

    template <class TYPE> 
    const HashTable<TYPE>& HashTable<TYPE>::operator=(const HashTable<TYPE>& other) 
    { 
     if(this != &other) 
     { 
      if(records) 
      { 
       for(int i = 0 ; i < TableSize; i++) 
        remove(records[i]->key_); 
       delete[] records ; 
      } 
      records = new Record*[other.TableSize] ; 
      TableSize = other.TableSize ; 
      for(int i = 0 ; i < other.TableSize ; i++) 
      { 
       update(records[i]->key_, records[i]->data_); 

      } 

     } 

     return *this; 

    } 

    template <class TYPE> 
    HashTable<TYPE>::HashTable(const HashTable<TYPE>& other) 
    { 
     if(other.records != nullptr) 
     { 
      if(records) 
      { 

       delete[] records ; 
       cout<<"delete"<<endl; 

      } 

      records = new Record*[other.TableSize]; 



      TableSize = other.TableSize; 
      for(int i = 0 ; i < other.TableSize; i++) 
       records[i] = new Record(); 

      for (int i = 0; i<other.TableSize; i++) 
      { 
       update(other.records[i]->key_, other.records[i]->data_); 
      } 

     } 
     else 
     { 
      records = nullptr; 
     } 

    } 

答えて

0
HashTable<TYPE>::HashTable(const HashTable<TYPE>& other) 
{ 
    // ... 
     if (records) { 
      delete[] records ; 

です。

あなたは新しいオブジェクトを作成していますが、そのメンバーはまだ初期化されていません(これは悪い習慣です)。初期化するのはあなたの責任であったものの価値を使うことはすでに悪いですが、そこに起こったジャンクを削除することは悲惨なことです。

あなたのoperator=には、既にオブジェクトが存在するので意味があります。