哈希表在增加大小后重新插入

时间:2013-06-08 03:55:41

标签: c++ hashtable

我一直在研究这个哈希表实现,但我遇到了障碍。我修改了构造函数并插入函数,以便在达到容量时调整数组大小,但是我遇到了调整大小的问题。现在,它似乎是无限插入负数据,我不知道为什么。我应该在resize中实现迭代器还是有更简单的方法呢?

以下是功能:

调整大小:

template <class RecordType>
void table<RecordType>::resize( )
{

    RecordType *oldData = data;
    int oldSize = CAPACITY;
    int newSize = CAPACITY *2;

    //create a new table
    RecordType *newData;
    newData = new RecordType[CAPACITY];

    size_t i;
    used = 0;

    for (i = 0; i < CAPACITY; i++)
        newData[i].key = NEVER_USED;

    data = newData;
    delete[] newData;

    //place data from old table to new, larger table.
    for(int i = 0; i < oldSize; i++)
    {
            RecordType next = oldData[i];
            insert(next);
    }

    CAPACITY = newSize;
    delete[] oldData;
}

构造

template <class RecordType>
table<RecordType>::table( )
{
    CAPACITY = 30;
    data = new RecordType[CAPACITY];

    size_t i;

    used = 0;
    for (i = 0; i < CAPACITY; ++i)
        data[i].key = NEVER_USED;

}

插入:

template <class RecordType>
void table<RecordType>::insert(const RecordType& entry)
// Library facilities used: cassert
{
    bool already_present;   // True if entry.key is already in the table
    size_t index;        // data[index] is location for the new entry

    assert(entry.key >= 0);

    // Set index so that data[index] is the spot to place the new entry.
    find_index(entry.key, already_present, index);

    // If the key wasn't already there, then find the location for the new entry.
    if (!already_present)
    {
        if (size( ) >= CAPACITY)
        {
            resize( ); // resize the table.

            insert(entry); // reinsert entry into new table.
        }
        else if (size( ) < CAPACITY)
        {
            index = hash(entry.key);

            while (!is_vacant(index))
                index = next_index(index);
            ++used;
        }
    }

    data[index] = entry;
    size_t i;
    for (i=0; i<CAPACITY; i++) cout << data[i].key << ' ';
    cout << endl;
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的resize()正在调用insert(),这会将数据放入data[]。然后resize()用空(满dataNEVER_USED数组覆盖newData。我的猜测是你要摆脱newData而只是使用data

您可能也应该重新考虑CAPACITY *= CAPACITY,因为当您尝试将此代码用于真实内容时,这会爆炸。