Professional C__ - Marc Gregoire [311]
(*mElems)[bucket].erase(it);
mSize--;
return 1;
} else {
return 0;
}
}
Code snippet from Hashmap\FinalHashmap\hashmap.cpp
The second form of erase() must remove the element at a specific iterator position. The iterator given is, of course, a HashIterator. Thus, the hashmap must have some ability to obtain the underlying bucket and list iterator from the HashIterator. The approach we take is to make the hashmap class a friend of the HashIterator (not shown in the preceding class definition).
template void hashmap typename hashmap { // Erase the element from its bucket. (*mElems)[position.mBucket].erase(position.mIt); mSize--; } Code snippet from Hashmap\FinalHashmap\hashmap.cpp The final version of erase() removes a range of elements. It iterates from first to last, calling erase() on each element, thus letting the previous version of erase() do all the work: template void hashmap typename hashmap typename hashmap { typename hashmap // Erase all the elements in the range. for (next = first; next != last; ) { cur = next++; erase(cur); } } Code snippet from Hashmap\FinalHashmap\hashmap.cpp hashmap Clear Operation The clear() method uses the for_each() algorithm to call clear() on the list representing each bucket: template void hashmap { // Call clear on each list. for_each(mElems->begin(), mElems->end(), [](ListType& e){e.clear();}); mSize = 0; } Code snippet from Hashmap\FinalHashmap\hashmap.cpp hashmap Accessor Operations The standard requires access methods for the key comparison and value comparison objects. These methods must be called key_comp() and value_comp(): template typename hashmap hashmap { return mComp; } template typename hashmap hashmap { return value_compare(mComp); } Code snippet from Hashmap\FinalHashmap\hashmap.cpp The find() method is identical to the version shown earlier for the basic hashmap, except for the return code. Instead of returning a pointer to the element, it constructs a HashIterator referring to it: template typename hashmap hashmap { size_t bucket; // Use the findElement() helper. auto it = findElement(x, bucket); if (it == (*mElems)[bucket].end()) { // We didn't find the element--return the end iterator. return end(); } // We found the element--convert the bucket/iterator to a HashIterator. return HashIterator } Code snippet from Hashmap\FinalHashmap\hashmap.cpp The const version of find() is identical, so its implementation is not shown here. The implementation of count() is a wrapper for find(), returning 1 if it finds the element, and 0 if it doesn’t. The find() method returns the end iterator if it can’t find the element. count() retrieves an end iterator by calling end() in order to compare it. Since this hashmap does not allow duplicate keys, count() always returns either 0 or 1: template typename hashmap hashmap { // There are either 1 or 0 elements matching key x. // If we can find a match, return 1, otherwise return 0. if (find(x) == end()) { return