Standard Template Library - PowerPoint PPT Presentation

About This Presentation
Title:

Standard Template Library

Description:

Standard Template Library There are 3 key components in the STL Containers Iterators Algorithms Promote reuse More debugged May be more efficient – PowerPoint PPT presentation

Number of Views:145
Avg rating:3.0/5.0
Slides: 61
Provided by: William1233
Category:

less

Transcript and Presenter's Notes

Title: Standard Template Library


1
Standard Template Library
  • There are 3 key components in the STL
  • Containers
  • Iterators
  • Algorithms
  • Promote reuse
  • More debugged
  • May be more efficient

2
Containers
  • There are 3 types of containers
  • Sequence containers
  • Associative containers
  • Container adapters
  • Sequence and Associative containers are first
    class containers
  • There are 4 near containers
  • C-like arrays
  • String
  • Bitset
  • Valarray high speed math

3
Container Classes
  • Sequence Containers just hold values.
  • vector 1D array rapid insertions and
    deletions at back direct access to elements
  • deque rapid insertions and deletions at front
    or back direct access to any element
  • list doubly linked list rapid insertions and
    deletions anywhere

4
Associative Containers
  • Associate values
  • set rapid lookup no duplicates
  • multiset rapid lookup duplicates allowed
  • map one to one mapping, no duplicates, rapid
    key lookup
  • multimap one to many mapping, duplicates
    allowed, rapid key based lookup

5
Container Adapters
  • These implement data structures that can be
    implemented with different containers
  • stack last in first out can be implemented
    with a vector, deque or a list.
  • queue first in first out
  • priority_queue highest priority is the first
    one out.

6
Member functions for all containers
  • Default constructor default initialization.
    There may be a variety of constructors for
    various initialization methods.
  • Copy constructor initializes a container to be
    a copy of the existing container.
  • Destructor
  • empty returns true or false
  • max_size returns max size

7
More member functions
  • size returns the current size
  • operator - assigns one container to another
  • operatorlt - returns true or false
  • operatorlt, gt, gt, , !
  • swap swap the elements of 2 containers.

8
First class member functions
  • These are only available to first class
    containers (sequence and associative)
  • begin return an iterator that refers to the
    first element of the container.
  • end return an iterator that refers to the
    position after the end of the container
  • rbegin return a reverse_iterator that refers to
    the last element of the container
  • rend - return a reverse_iterator that refers to
    the position before the first element of the
    container
  • erase erases one or more elements
  • clear erases all elements from the container.

9
Using the STL
  • Many implementations of the STL are different
    than normal libraries
  • Some use the following method (using the vector
    class).
  • include ltvectorgt
  • using namespace std
  • Notice, no .h in the file name.
  • Some implementations may work with the .h and no
    using.

10
The STL header files
  • The header files are in
  • ltvectorgt
  • ltlistgt
  • ltdequegt
  • ltqueuegt
  • ltstackgt
  • ltmapgt
  • ltsetgt
  • ltbitsetgt

11
Typedefs
  • The following are typedefs defined in the first
    class containers.
  • value_type the type of element stored in the
    container
  • reference a reference to the type of element
    stored in the container
  • const_reference reference that cannot change
    the contents of the container
  • pointer a pointer to the type of element stored
    in the container
  • iterator an iterator type to the element

12
More typedefs
  • const_iterator
  • reverse_iterator for going backwards in the
    container
  • const_reverse_iterator
  • difference_type the type of the result of
    subtracting 2 iterators to the same container.
  • size_type the type used to count items in a
    container and index through a sequence container

13
Iterators
  • Iterators are a lot like pointers. They tell
    where something is.
  • An Iterator is implemented as a class
  • This prevents many errors
  • Allows as many iterators as you want for a class
    in both the implementation of the class and the
    using of the class

14
Iterator Categories
  • Input used to read an element from a container.
    Can only move forward. Can only go through the
    sequence once.
  • Output used to write an element to a container.
    Can only move forward. Only one pass.
  • Forward combines input and output and retain
    position in container
  • Bi-directional combines input and output and
    allows backward movement. Can have more than one
    pass.
  • Random access can jump to any element.

15
Iterators supported
  • vector random and above
  • deque random and above
  • list bi-directional and above
  • set bi-directional and above
  • multiset bi-directional and above
  • map bi-directional and above
  • multimap bi-directional and above
  • stack none
  • queue none
  • priority_queue none

16
Iterator Operations
  • The following are for all iterator types
  • p preincrement
  • p - postincrement
  • Input iterators
  • p dereference an iterator for an rvalue
  • pp1 assign iterators
  • pp1 compare for equality
  • p!p1 compare for inequality
  • Output iterators
  • p dereference for use as lvalue
  • pp1 assign iterators

17
More iterator operators
  • Forward operators
  • Same as input and output
  • Bi-directional iterators
  • --p predecrement
  • p-- - postdecrement
  • Random-Access iterators
  • pi increment p by i positions
  • p-i decrement p by i positions
  • pi p incremented by i positions
  • p-i
  • pi return a reference to the element offset
    from p by i positions
  • pltp1 true if p is before p1
  • pgtp1, pgtp1, pltp1

18
Algorithms
  • Algorithms are generic functions that work across
    all the containers.
  • They are not member functions of a container
    class.
  • This way the algorithms can be written without
    being rewritten for each class.
  • Many algorithms work on a sequence by being sent
    a begin and end iterator.

19
Mutating sequence algorithms
copy() transform() unique_copy() copy_backward()
generate() unique() generate_n() swap_ranges()
rotate() remove() remove_copy() remove_copy_if()
replace() reverse() replace_copy_if() reverse_copy()
fill() partition() rotate_copy() stable_partition()
swap() iter_swap() replace_copy() remove_if()
fill_n() replace_if() random_shuffle()
20
Non Mutating sequence alg.
adjacent-find() count()
count_if() equal()
find() for_each()
mismatch() search()
search_n()
21
Numerical Algorithms
  • Need to use header ltnumericgt
  • accumulate()
  • inner_product()
  • partial_sum()
  • adjacent_difference()

22
Tips part 1
  • For any particular application, several different
    STL containers could be appropriate. Select the
    most appropriate container that achieves the best
    performance for that application.
  • STL capabilities are implemented to operate
    efficiently across a wide variety of
    applications. You may need to write your own
    customized implementations for specialized
    applications.

23
Tips part 2
  • The STL approach allows general programs to be
    written so the code does not depend on the
    underlying container.
  • STL avoids inheritance to achieve best run time
    performance.
  • Know STL components. Choose the most appropriate
    container for your application.
  • Attempting to dereference an iterator outside the
    container is an error. In particular,
    dereferencing end() will be an error.

24
Tips part 3
  • STL is extensible. It is straightforward to add
    new algorithms and to do so without changes to
    STL containers.
  • STL algorithms can operate on STL containers and
    on pointer based C-like arrays.
  • Since STL algorithms process many containers
    through iterators, one algorithm can often be
    used with many containers.

25
Tips, part 4
  • Applications that require frequent insertions and
    deletions at both ends of a container normally
    use a deque rather than a vector.
  • Applications with frequent insertions and
    deletions in the middle of a container normally
    use a list.
  • The vector container is best for random access.
  • It is faster to insert many items at once than
    one at a time.

26
Sequence containers
  • Vector and deque are based on arrays.
  • List is a linked list data structure.
  • Vector is a smart array. It can change size
    dynamically. When a vector needs more space, it
    reallocates an array of twice the size and copies
    the old contents into the new array. Can do
    vector assignment.
  • Vector subscripting does not perform range
    checking. Use the member function at.

27
Sequence Container Operations
  • The sequence containers also have the operations
  • push_back insert at the end
  • pop_back remove from the end

28
The vector Sequence Container
  • Uses contiguous memory locations
  • Supports random access iterators
  • Can use all the iterator functions
  • All STL algorithms can operate on a vector.

29
Code with vector
  • includeltvectorgt
  • using namespace std
  • void main()
  • vectorltintgt v
  • v.push_back(2)
  • v.push_back(3)
  • v.push_back(4)
  • coutltltv.size()ltltv.capacity()ltltendl
  • vectorltintgtconst_iterator p1
  • for (p1v.begin() p1!v.end() p1)
  • cout ltlt p1
  • vectorltintgtreverse_iterator p2
  • for (p2v.rbegin() p2 ! v.rend() p2)
  • coutltltp2

30
Vector functions
  • Copy Constructor
  • vectorlttypegt v(a, aSIZE)
  • Creates v with a copy of a (which is a vector or
    c-type array) from beginning (a) to the end
    (aSIZE, the one at aSIZE is not copied).
  • copy(a.begin(), a.end(), v.begin())
  • Remember, front and back cannot be used on an
    empty vector.

31
Addressing
  • There are several ways to address an element of a
    vector.
  • vivalue
  • v.at(i)value //subscript checking
  • v.insert(v.begin()i, value)// moves rest
  • v.insert(pos, otherstart, otherend)
  • v.erase(v.begin()i)
  • v.erase(begin, end)
  • v.clear()//erases all
  • If the element is a pointer, the erase does not
    delete the element.

32
List Operations
  • myl.push_front(value)
  • myl.pop_front(value)
  • myl.splice(myl_pos, otherlist)
  • Remove elements in otherlist and put before
    myl_pos in myl
  • myl.splice(myl_pos, otherlist, other_pos) //
    move 1 element
  • myl.splice(myl_pos, otherlist, other_start,
    other_end)

33
More List Operations
  • myl.remove(myl_pos)
  • myl.sort()
  • myl.sort(bool cmp(type, type))
  • Sort using a comparison function (needed for list
    of records).
  • myl.unique()
  • Remove duplicates in a sorted list.
  • Need bool function for equality if not using the
    default.
  • myl.merge(other)
  • Takes 2 sorted lists and merges them
  • Can add a bool function for merge condition.

34
Last of List operations
  • myl.reverse()
  • myl.swap(other)
  • Swaps the entire container
  • myl.assign(other_start, other_end)
  • Make myl contain only part of other.

35
Deque Operations
  • Has basically the same functions as vector
  • Additionally there are
  • push_front
  • pop_front

36
Associative classes
  • These containers are key oriented
  • Set and multiset just have a key set is for
    unique values, and multiset allows duplicate
    values.
  • Map and multimap have a record associated with
    each key.
  • All associative containers can
  • find
  • lower_bound
  • upper_bound
  • count

37
Multiset
  • There are built in comparison templated functions
    lesslttypegt and greaterlttypegt
  • Need to have lt and gt defined on the type.
  • Kept in order
  • The order is determined by a comparator function
    object given during creation.
  • Supports bidirectional iterators
  • Uses a somewhat balanced tree to implement

38
Operations
  • Must use the include file ltsetgt
  • Contains both the set and multiset classes
  • Constructor
  • multisetltkeytype, cmplttypegt gt
  • cmp is less or greater
  • insert(value)
  • int count(value) how many of value are in the
    multiset (not used in set).
  • iterator find(value) gives an iterator to the
    value if found returns end() if not found.

39
More Methods
  • void insert(arraystart, arrayend) adds many
    values to the multiset.
  • The pair class
  • pairlttype1, type2gt pobj
  • This is a class to hold 2 values.
  • Data is public
  • pobj.first and pobj.second
  • pair equal_range(value) returns an iterator
    pair pointing to the beginning and end of the
    range containing the single value
  • pairltmultisetltintgtiterator, multisetltintgtitera
    torgt p
  • pmyset.equal_range(37)

40
Set
  • No duplicates
  • The insert function returns an iterator, bool
    pair.
  • If the insert worked (not a duplicate), the bool
    is true and the iterator points to where it was
    inserted.
  • If the insert failed (tried to insert a
    duplicate), bool is false and the iterator value
    is unimportant.

41
Multimap
  • Use the header ltmapgt for both map and multimap.
  • Methods
  • multimapltkeytype, recordtype, cmpgt mobj
  • int count(keyvalue)
  • void insert(pair)
  • multimaplttype1, type2, cmpgtvalue_type(v1, v2)
  • Creates a pair with v1 and v2
  • iterators point to a pair
  • itr-gtfirst
  • itr-gtsecond

42
Map
  • Same functions and idea as multimap, just no
    duplicates.
  • Can use mobjkey
  • This is not a subscript
  • It returns a reference to a position (who knows
    where) associated with that key.
  • You can place values there or use the values from
    there.

43
Stack Adapter
  • Implemented with a vector, list or deque
    (default).
  • void push(value)
  • void pop()
  • type top()
  • bool empty()
  • int size()
  • stacklttype, vectorlttypegt gtstk
  • stacklttypegt stk

44
Queue Adaptor
  • Implemented with a list or a deque (default).
  • push add to back
  • pop remove from front
  • front get first value
  • back get last value
  • empty size

45
Priority Queue
  • Implemented with a deque or vector (default).
  • Uses a heap principle
  • push
  • pop
  • top
  • empty
  • Size

46
Algorithms
  • fill(iter_start, iter_end, value)
  • Fill the container from start to end with value.
  • fill_n(iter_start, count, value)
  • Fill the container with count copies of value
    starting at start.
  • generate(start, end, function)
  • Function returns value of type, takes no arg.
    Places return value in container. Called several
    times.
  • generate_n(start, count, function)

47
More Algorithms
  • bool equal(start1, end1, start2)
  • Returns true if all values between start and end
    of container1 are the same as the corresponding
    values in container2.
  • bool equal(start1, end1, start2, func)
  • Func is an equality boolean function that takes 2
    args of type.
  • pairltiter, itergt mismatch(s1, e1,s2)
  • Returns a pair of iterators for the first case of
    a value in container1 not equal to the
    corresponding value in container2.
  • pairltgt mismatch(s1, e1,s2, func)

48
Algorithms again
  • bool lexicographical_compare(s1,e1,s2 , e2)
  • Used mainly with strings. Returns true if the
    first container is less than second
    lexicographically.
  • remove(s,e,value)
  • Remove all occurances of value between s and e.
  • remove_copy(s1,e1,s2,value)
  • s2 has a copy of s1 with instances of value
    removed
  • remove_if(s,e,bool_func)
  • Removes the value when bool_func is true
  • Remove_copy_if(s1,e1,s2, bool_func)

49
Even More
  • replace(s,e,old_value,new_value)
  • replace_if(s,e, bool_func, new)
  • Replaces value with new if old passed to
    bool_func returns true.
  • replace_copy(s1,e1,s2, old,new)
  • Makes a copy of the container with instances of
    old value replaced with new value.
  • replace_copy_if(s1,e1,s2, bool_func,new)

50
Math type functions
  • random_shuffle(begin, end)
  • Change the order of items between begin and end.
  • count(begin, end, value)
  • Give a count of items with value
  • count_if(begin, end, bool_func)
  • min_element(begin, end)
  • max_element(begin, end)
  • Min and max return iterators.

51
More math
  • accumulate(s,e,start_value)
  • Adds up values
  • accumulate(s,e,start_value,func)
  • func tells how to accumulate (can multiply,
    etc.). func takes 2 args, the partial result and
    the new value.
  • for_each(s,e,func)
  • Passes values between s and e to func
  • transform(s1,e1,s2, func)
  • Passes each value from s to e to func and places
    the result in container2.

52
Searching
  • find(s,e,value)
  • Returns an iterator to the element with value.
  • find_if(s,e,bool_func)
  • Returns an iterator to an element that makes
    bool_func true.
  • sort(s,e)
  • bool binary_search(s,e,value)

53
Swapping
  • swap(ref, ref)
  • Takes 2 references and swaps the values
  • iter_swap(iter, iter)
  • Takes 2 iterators and swaps the values
  • swap_ranges(start1, end1, start2)
  • Swap the elements from start1 to end1 with the
    same number of elements starting at start2

54
More algorithms
  • copy_backward(start1, end1, end2)
  • Copies from start1 up to end1 placing the values
    starting at end2 and working backward. Returns
    iterator positioned at the beginning of the
    resulting list.
  • merge(s1,e1,s2,e2,rstart)
  • Merge the sorted values from s1 to e1 with the
    sorted values from s2 to e2 into the container
    starting at rstart. Can also have a cmp function
    for order

55
Other Algorithms
  • unique(start, end)
  • Removes duplicates
  • unique_copy(s1,e1,s2)
  • reverse(start,end)
  • Reverses all the elements
  • reverse_copy(s1,e1,s2)
  • inplace_merge(s1,s2,e2)
  • Merges 2 sorted sequences from the same container
    back into the same container. Merges from s1 to
    s2 with from s2 to e2.

56
Set Operations
  • Values must be ordered in container
  • bool includes(s1,e1,s2,e2)
  • Returns true if the set from s2 to e2 is
    contained in the set from s1 to e1
  • set_difference(s1,e1,s2,e2,r1)
  • Places all the values that are in container 1 but
    not in container 2 into container r.
  • set_intersection(s1,e1,s2,e2,r1)
  • Places values that are in both container 1 and
    container 2 into container r.

57
Last of set operations
  • set_symmetric_difference(s1,e1,s2,e2,r1)
  • Place values that are in container 1 but not in
    container 2 into container r and place values
    that are in container 2 but not in container 1
    into container r.
  • set_union(s1,e1,s2,e2,r1)
  • Place the union of containers 1 and 2 into
    container r.

58
Ranges
  • lower_bound(s,e, value)
  • Returns an iterator that gives the first position
    where value could be inserted in sorted order.
  • upper_bound(s,e,value)
  • Returns an iterator that gives the last position
    where a value could be inserted in sorted order.
  • equal_range(s,e,value)
  • Returns a pair of iterators that are the same as
    calling lower and upper bound

59
Heapsort
  • make_heap(s,e)
  • Makes a heap in the container
  • sort_heap(s,e)
  • Sort values that are already in a heap
  • push_heap(s,e)
  • Used after a push_back function call. Makes a
    heap out of what was a heap with one item added.

60
Last ones
  • min(value1, value2)
  • max(value1,value2)
Write a Comment
User Comments (0)
About PowerShow.com