Sets Maps and Hash Tables Review
Sets Maps and Hash Tables Review
REVIEW
Operations:
l
m
A B A B A B A B
std::set<type> s; std::unordered_set<type> s;
s.insert(5); s.insert(5);
s.insert(2); s.insert(2);
s.insert(4); s.insert(4);
s.insert(11); s.insert(11);
s.insert(2); // wont add 2 again s.insert(2); // wont add 2 again
// printing set using iterator yields: // printing set using iterator yields:
2, 4, 5, 11 11, 4, 5, 2
Many-to-one relationship
(Onto Mapping)
Operations:
std::map<type key, type value> m; → Ordered std::unordered_map<type key, type value> m; → Not Ordered
Implemented as: BST Implemented as: Hash Table Clearly faster than
Time complexity: Time complexity: ordered maps :D
insert = O(log(n)), insert average case = O(1)
[] = O(log(n)) [] average case = O(1)
//printing using an iterator will yield: //printing using an iterator will yield:
a : 40 c : 50
b : 30 Prints in order of keys b : 30 Does not print in any sort of order
c : 50 a : 40
Hash Table – uses a hash function to compute an index (a hash code) which maps to a “bucket” containing value
Having a good hash function is critical for hash table efficiency… value = yummy
Then let’s say we insert the key “Julia” (length = 5) John (length = 4)
4%4=0
Load factor now becomes 1 entry / 4 buckets = 0.25
888-555-1111
Then we insert “John” (length = 4)
1. Separate chaining: each bucket stores a linked list; collisions are simply appended to the end of the list
Julia (length = 5)
5%4=1
John (length = 4)
4%4=0
888-555-1111 777-666-5555
222-333-4444
Mariannae (length = 4)
9%4=1
2. Open Addressing (Linear Probing): each bucket stores only one entry; if you try to add and entry and there is a
collision, move the “problem” entry (one bucket at a time) to the next available free bucket and put it there
3. Open Addressing (Quadratic Probing): same as linear probing, except you move the “problem” entry 1 bucket, then by
4 buckets, then by 9 buckets then by 16 buckets, etc.