13.2 Analysis of hash tables and STL maps. Compare hash tables and STL maps. How is a hash table implemented? If the input data size is small, we can use what data structure instead of hash table.
Answer
Compare hash tables and STL maps
In a hash table, the stored location of the real value is determined by the hash function value corresponding to its key value. Therefore, the values stored in the hash table are unordered. The time complexity of inserting elements and finding elements in a hash table is O (1). (assuming little conflict). To implement a hash table, conflict handling is an important consideration.
For maps in STL, key/value pairs are sorted by key. It uses a red-black tree to hold the data, so the time complexity of inserting and locating elements is O (Logn). And there is no need to deal with conflict issues. The map in the STL is suitable for the following scenarios:
- Find the smallest element
- Find the largest element
- Output elements in an orderly manner
- Finds an element, or finds the smallest element larger than it when the element is not found
How the hash table is implemented
- First, a good hash function is required to ensure that the hashes are evenly distributed. For example, to take a model for a large prime number
- Second, a good conflict resolution is needed: the linked list method (chaining, which uses this method when the elements in the table are relatively dense), the detection method (probing, open address method, and the table where the elements are relatively sparse).
- Dynamically increases or decreases the size of the hash table. For example, if (the number of elements in the table)/(table size) is greater than a threshold value, the hash table size is increased. We create a new large hash table and then map the values of the elements in the old table to the new table through the new hash function.
If the input data size is small, we can use what data structure instead of hash table.
You can use STL maps instead of hash tables, although the time complexity of inserting and locating elements is O (Logn), but because the size of the input data is small, this time difference can be negligible.
Careercup-c and C + + 13.2