C++ STL hash conflicts are handled in the following ways: Chain address method: Use a linked list to store conflicting elements, which has good applicability. Open addressing method: Find available locations in the bucket to store elements. The sub-methods are: Linear detection: Find the next available location in sequence. Quadratic Detection: Search by skipping positions in quadratic form.
When using the hash table of the C++ Standard Template Library (STL), conflicts are inevitable because Multiple keys may hash to the same bucket. To handle conflicts, STL provides the following methods:
The chain address method uses a linked list to store elements hashed into the same bucket. When a conflict occurs, a new linked list node is created and the element is added to the linked list. This is the most commonly used collision handling method because it handles dense hash tables well.
#include <unordered_map> #include <list> int main() { std::unordered_map<int, std::list<int>> hash_table; hash_table[10].push_back(100); hash_table[10].push_back(200); // 迭代哈希到 10 的键 for (auto& item : hash_table[10]) { std::cout << item << " "; // 输出 100 200 } return 0; }
The open addressing method will not create new nodes when a conflict occurs. Instead, it looks for the next available location in the bucket to store the element. There are several open addressing methods, the most common of which are linear probing and quadratic probing.
Linear detection:
#include <unordered_map> int main() { std::unordered_map<int, int> hash_table; hash_table[10] = 100; // 插入 (10, 100) hash_table[10] = 200; // 更新 (10, 200) // 访问更新后的值 std::cout << hash_table[10] << std::endl; // 输出 200 return 0; }
Secondary detection:
#include <unordered_map> int main() { std::unordered_map<int, int, std::hash<int>, std::equal_to<int>, QuadraticProbing<int, int>> hash_table; hash_table[10] = 100; // 插入 (10, 100) hash_table[10] = 200; // 更新 (10, 200) // 访问更新后的值 std::cout << hash_table[10] << std::endl; // 输出 200 return 0; }
Which conflict handling method is chosen depends on the hash table expected loading factor. The chain addressing method is generally more suitable for dense hash tables, while the open addressing method is more suitable for sparse hash tables.
The above is the detailed content of How to deal with hash collisions when using C++ STL?. For more information, please follow other related articles on the PHP Chinese website!