Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

## Имя студента

*Пожалуйста, добавьте вместо курсивного текста своё ФИО.*
Суржиков Ярослав Сергеевич

## Описание задания

Expand Down
48 changes: 39 additions & 9 deletions src/hash_table.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,60 @@ namespace itis {
throw std::logic_error("hash table load factor must be in range [0...1]");
}

// Tip: allocate hash-table buckets
for (int i = 0; i < capacity; i++){
buckets_.emplace_back(Bucket());
}
}

std::optional<std::string> HashTable::Search(int key) const {
// Tip: compute hash code (index) and use linear search
int index = hash(key);
for (const auto& bucket : buckets_[index]){
if (bucket.first == key){
return bucket.second;
}
}
return std::nullopt;
}

void HashTable::Put(int key, const std::string &value) {
// Tip 1: compute hash code (index) to determine which bucket to use
// Tip 2: consider the case when the key exists (read the docs in the header file)
int index = hash(key);
for (auto &bucket : buckets_[index]){
if (bucket.first == key) {
bucket.second = value;
return;
}
}
buckets_[index].push_back(std::pair(key, value));
num_keys_ += 1;

if (static_cast<double>(num_keys_) / buckets_.size() >= load_factor_) {
// Tip 3: recompute hash codes (indices) for key-value pairs (create a new hash-table)
// Tip 4: use utils::hash(key, size) to compute new indices for key-value pairs
auto new_size = buckets_.size() * kGrowthCoefficient;
std::vector<Bucket> temp_buckets;
temp_buckets.resize(new_size);
for (auto &bucket: buckets_){
for (std::pair<int, std::string> &pair: bucket){
int i = utils::hash(pair.first, new_size);
temp_buckets[i].push_back(pair);
}
}
buckets_ =temp_buckets;
}
}

std::optional<std::string> HashTable::Remove(int key) {
// Tip 1: compute hash code (index) to determine which bucket to use
// TIp 2: find the key-value pair to remove and make a copy of value to return
return std::nullopt;
int index = hash(key);
std::optional<std::string> nullopt;
for (auto &bucket : buckets_[index]){
if (bucket.first == key){
nullopt = bucket.second;
buckets_[index].remove(bucket);
break;
}
}
return nullopt;
}


bool HashTable::ContainsKey(int key) const {
// Note: uses Search(key) which is not initially implemented
return Search(key).has_value();
Expand Down