extending stl

6
Extending STL when more is needed

Upload: huyen

Post on 05-Jan-2016

13 views

Category:

Documents


0 download

DESCRIPTION

Extending STL. when more is needed. Iterator Review. input (read) – read only access, forward-only, can be assigned and copied forward – read/write access, forward-only, can be assigned and copied bidirectional – same as forward plus can move backward - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Extending STL

Extending STL

when more is needed

Page 2: Extending STL

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

Page 3: Extending STL

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

Page 4: Extending STL

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

Page 5: Extending STL

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

Page 6: Extending STL

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