【问题标题】:C++ HashTable issue with find function查找函数的 C++ HashTable 问题
【发布时间】:2016-11-21 00:56:42
【问题描述】:

我正在尝试在这里编写 HashTable。我已经对所有函数进行了几乎所有的编码,并且程序正在使用 main 编译。但由于某种原因,我的 find 函数需要永远与我拥有的 main 一起运行。此外,当测试复制构造函数和 operator= 时,程序崩溃了。下面是哈希表

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;
        }

    }

【问题讨论】:

    标签: c++ hashtable


    【解决方案1】:
    HashTable<TYPE>::HashTable(const HashTable<TYPE>& other)
    {
        // ...
            if (records) {
                delete[] records ;
    

    没有什么情况可以这样做。

    您正在构建一个新对象,但尚未初始化它的任何成员(这本身就是不好的做法)。使用你有责任初始化的东西的值已经很糟糕了,但是删除其中发生的任何垃圾都可能是灾难性的。

    在您的operator= 中确实有意义,因为该对象已经存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-25
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 2011-10-14
      • 2016-03-28
      相关资源
      最近更新 更多