動的なサイズ変更を可能にするために、ハッシュ テーブルの実装を調整する割り当てが与えられました。手がかりと情報を探し回りましたが、ハッシュ テーブルがどのように動作するか、したがってサイズ変更をどのように行うべきかについて、まだ混乱しています。サイズ変更関数を追加し、挿入で呼び出し、コンストラクターを変更する必要があると言われました。私は挿入を正しく行ったと思いますが、十分に単純に思えますが、サイズ変更自体とコンストラクターは私が苦労しているものです。
編集:サイズ変更関数、挿入、およびコンストラクターに取り組んできましたが、古いデータをより大きなテーブルに挿入するために resize() の for ループでエラーが発生し、何が問題なのかわかりません. 何か案は?
ヘッダーは次のとおりです。
#ifndef TABLE1_H
#define TABLE1_H
#include <cstdlib> // Provides size_t
#include <cassert> // Provides assert
namespace main_savitch_12A
{
template <class RecordType>
class table
{
public:
size_t CAPACITY;
// CONSTRUCTOR
table( );
// MODIFICATION MEMBER FUNCTIONS
void insert(const RecordType& entry);
void remove(int key);
void resize( );
// CONSTANT MEMBER FUNCTIONS
bool is_present(int key) const;
void find(int key, bool& found, RecordType& result) const;
size_t size( ) const { return used; }
private:
// MEMBER CONSTANTS -- These are used in the key field of special records.
enum { NEVER_USED = -1 };
enum { PREVIOUSLY_USED = -2 };
// MEMBER VARIABLES
RecordType *data; //[CAPACITY];
size_t used;
// HELPER FUNCTIONS
size_t hash(int key) const;
size_t next_index(size_t index) const;
void find_index(int key, bool& found, size_t& index) const;
bool never_used(size_t index) const;
bool is_vacant(size_t index) const;
};
コンストラクターの実装:
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>::resize( )
{
RecordType *oldData = data;
int oldSize = CAPACITY;
CAPACITY *= CAPACITY;
//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;
//place data from old table to new, larger table.
for (int i = 0; i < oldSize; i++)
{
insert(newData[hash(i)]); //this is where I'm having trouble.
}
data = newData;
delete[] oldData;
}
挿入実装:
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;
}
助けてくれてありがとう!