Download - Extending STL
Extending STL
when more is needed
Algorithms• extending STL with specialized algorithms is relatively straightforward
• algorithm find_all– implemented as template
– takes an iterator range and a predicate and returns a vector of iterators pointing to values that match predicate
• internally uses find_if
2
Container Example: Hashmap• hashmap a variant of unordered_map developed from scratch
• we start with a basic hashmap that does not implement iterators and cannot be used with STL algorithms
• elements – key, value pairs
• hashes, or maps, a key to a bucket
• implements a vector of buckets with a list of <key,values> at each bucket (chained hashing)
3
Hashmap: Hash• hash – hashing function
• clients may provide their own, specify number of buckets• DefaultHash a separate class - default implementation, accepts numBuckets
computes a sum of bytes in a key, modulo numBuckets– basic hash, key uniformity is not achieved
4
Hashmap: Interface & Implementation• supports three basic functions: insertion, deletion and lookup
• constructor, destructor, copy constructor, (basic) copy assignment, (c++11) move, (c++11) move assignment
• template parameters
– key
– value
– compare – by default an equal_to functor for comparison – to detect attempts to insert elements with duplicate keys
– hash – by default DefaultHash
• implementation
– fixed size (number of buckets) vector of pointers to lists containing <key, value> pairs
– comparison object
– hash object
– number of elements in the container
5
Hashmap: Element Lookup• helper method findElement() –, then looks into bucket to find element, using
functor for comparison, if not found returns end of bucket
– note the use of typename in return value – needed because template parameters are used
• find() - a wrapper around findElement()• operator[] – uses find() to determine if element present
– if yes – returns it
– if not – use insert() to insert it, find() to find and return it• insert() – finds using findElement() if not found - insert
6