Standard Template Library - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

Standard Template Library

Description:

Explain the types of components in the STL ... MultiMap. Map. Link key & value (Lookup(key)) MultiSet (bag) Set. Just store key (Is key present? ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 25
Provided by: julie57
Category:

less

Transcript and Presenter's Notes

Title: Standard Template Library


1
Standard Template Library
  • Describe the goals of the STL
  • Explain the types of components in the STL
  • Algorithms, containers, iterators, function
    objects, adaptors
  • Give examples of STL components
  • Explain the definition of constraints on items
  • Logical (functional) constraints
  • Complexity (performance) constraints
  • See The Standard Template Library, Alexander
    Stepanov, Meng Lee (http//www.stepanovpapers.com
    /STL/DOC.PDF)

2
What is the STL?
  • A library of useful facilities based on templates
  • For example,
  • Commonly used collection classes
  • Why use templates could use void pointers
  • Reuse
  • Uses a different style of programming
  • Clever use of templates
  • Some of the design concepts are described in
  • The Standard Template Library, Alexander Stepanov
  • (http//www.stepanovpapers.com/BYTE_com.htm)

3
STL Goals
  • Compatibility
  • template algorithms work with STL built-in data
    types
  • Can use library data structures with your
    algorithms,
  • Can use library algorithms with your data
    structures
  • Well-specified semantic and complexity
    requirements
  • Ensure user components will work with STL do so
    efficiently
  • Efficiency
  • Competitive with hand-coded versions
  • Concise
  • Reduce duplication maximise reuse
  • Easy to understand
  • Theoretically sound

After studying, assess this for yourself
4
Types of STL components
  • Algorithm
  • defines a computation e.g. sort.
  • Container
  • manages a set of items.
  • Iterator
  • provides a way to access the items in a
    container.
  • Function object
  • encapsulates a function for use by other
    components.
  • Adaptor
  • adapts a component to provide a different
    interface.
  • e.g. convert a vector collection to a stack

5
Requirements
X might not be a class
  • Necessary constraints for items to work together
  • E.g. if a template algorithm creates an array of
    X,
  • X must have a default constructor
  • Express in a general way
  • Better to say an array of X can be created. Why?
  • Not class X defines a member function
    operator()
  • But for any object x of class X, x is
    defined.
  • Allow the operator to be either a member or a
    global function.
  • Define valid expressions for item
  • Can include logical and efficiency requirements
  • E.g. must take linear time (This allows constant
    time)

6
Complexity Requirements
  • Defined using asymptotic complexity
  • A measure of time/memory for large inputs
  • Constant same time for any number of items (N)
  • Linear time roughly proportional to number of
    items
  • Quadratic time proportional to N2
  • log N if N 2p, time proportional to p
  • Averaged (amortised) over many calls
  • E.g list using an array doubles size when
    filled
  • insertAtEnd on average will be close to constant
    time
  • Even though occasionally an insertion will be
    proportional to N
  • Average / Worst case
  • Clearly state which

7
Core Components 1
  • Widely used template functions classes
  • Define logical operators based on gt
  • template ltclass T1, class T2gt
  • inline bool operator!(const T1 x, const T2 y)
  • return !(x y)
  • Example
  • person a
  • if (a ! y)
  • // If ! isnt defined, compiler generates the
    operator

Why?
8
Core Components 2
  • Template class to construct heterogeneous pairs
  • template ltclass T1, class T2gt
  • struct pair
  • T1 first
  • T2 second
  • pair()
  • pair(const T1 x, const T2 y) first(x),
    second(y)
  • e.g return pairltint, chargt(5, a) // have to
    explicitly name types

What other operators are needed?


Allows return make_pair(5, a) // deduces types
template ltclass T1, class T2gt inline pairltT1, T2gt
make_pair(const T1 x, const T2 y) return
pairltT1, T2gt(x, y)
9
Iterators
  • Iterators are objects that generalise pointers
  • Have an operator returning a value of a type T
  • x myIterator
  • Allow stepping through a collection using
  • y myIterator
  • Can find distance between two iterators
  • Like pointer arithmetic the number of steps
    between them
  • size endIterator myIterator
  • A template function using iterators can use
    pointers
  • Can return a past the end value (like NULL)
  • while (myIterator ! endIterator)
  • myArrayi myIterator

10
Iterators 2
  • Types of iterator
  • forward, bidirectional random access
  • Can be mutable or constant (value is reference or
    const ref)
  • input, output

Forward Iterator
bidirectional Iterator
Random access Iterator
1
2
3
4
5
11
Similar Concept
Match the similar items
  • cin
  • cout
  • Pointer into singly linked list
  • Pointer into doubly linked list
  • Pointer into array
  • Input iterator
  • Output iterator
  • Forward iterator
  • Bidirectional iterator
  • Random iterator
  • cin
  • Pointer into array
  • Pointer into doubly linked list
  • cout
  • Pointer into singly linked list

12
Example of constraints
  • Type X can be an output iterator if these are
    valid
  • X is an output iterator returning objects of type
    T,
  • a is a value of X, u is an identifier and r is a
    value of X
  • These are the simplest example of iterator
    constraints.
  • They mean that an output iterator is like a
    pointer into an output stream
  • Can write out one value after another.
  • Must write a value before moving on
  • Cant write twice to an output position

13
Notes
  • Algorithms for output iterators can use ostreams
  • Only use operator for output iterator as Lvalue
  • On the left of
  • Any output iterator value should be assigned
    through before it is incremented
  • i.e. if i is an output iterator, i i is not
    valid
  • Two copies of an output iterator value cant be
    active at the same time
  • e.g, i j i a j b is not valid
  • Discard original after copy
  • Why allow a copy (hint parameters)

14
Containers
  • Objects that store other objects
  • Control allocation and de-allocation of objects
  • through constructors, destructors, insert and
    erase
  • Value / Reference semantics?
  • Types of container
  • Define operations costs
  • Basic operations supported by all containers
  • Reversible containers
  • Supports bidirectional random access iterators
  • Sequences Vector, list, deque
  • Support accessing items one after another

STL containers use value semantics
15
Container Types
  • vector
  • Supports random access iterators
  • Insert and erase operations
  • (amortized) constant time at the end
  • linear time in the middle
  • list
  • Supports bidirectional but not random access
    iterators
  • Constant time insert and erase anywhere
  • deque
  • Like vector but optimised for insert/erase at
    start/end

16
Example Container Constraints
17
Associative Containers
  • Quickly retrieve data based on keys

18
Algorithms
  • Independent of data structures
  • work with user-defined data structures
  • If they have the appropriate iterators
  • May provide in-place and copying versions
  • In-place modifies a parameter
  • Copying returns new results
  • Algorithms ending with _if expect a predicate
  • Predicate (e.g. isEven())
  • a function object returns boolean when passed an
    item
  • binary_predicate (e.g. isEqual)
  • Returns boolean given two items

19
Example Algorithms
  • For each (for_each)
  • Apply a function to every item in the range
  • Find
  • Returns the position in range firstltpltlast of
    an item satisfying a predicate
  • Adjacent Find
  • Find position where neighbouring items satisfy a
    binary predicate
  • E.g. first position of out of order items
  • Count (count, count_if)
  • Set operations union, intersection
  • Sort

20
Example Mutating Algorithms
  • Copy
  • Swap
  • Transform
  • template ltclass InIter, class OutIter, class
    UnaryOpgt
  • OutIter transform(InIter first, InIter last,
    OutIter result, UnaryOp op)
  • template ltclass InIter 1, class InIter2, class
    OutIter, class BinaryOpgt
  • OutIter transform(InIter1 first1, InIter1 last1,
    InIter2 first2, OutIter result, BinaryOp bop)
  • Generate result from input sequences using
    operation
  • Generate create a sequence from a function
  • Unique strip out duplicates
  • Partition Put items satisfying a predicate to
    front

21
Function Objects
Yes! An operator called ()
  • Objects with an operator() defined
  • Passed to an algorithm instead of a pointer to a
    function
  • pointers to functions can still be used
  • E.g. by-element addition of vectors a and b of
    double putting result in a
  • transform(a.begin(), a.end(), b.begin(),
    a.begin(), plusltdoublegt())
  • template ltclass Tgt
  • struct plus binary_functionltT, T, Tgt
  • T operator()(const T x, const T y) const
    return x y
  • template ltclass Arg1, class Arg2, class Resultgt
  • struct binary_function
  • typedef Arg1 first_argument_type
  • typedef Arg2 second_argument_type
  • typedef Result result_type

Applies the function object plus to combine two
vectors an item at a time for (i0
ilta.length() i) ai plus(ai, bi)
Create names to stand-in for input output types
22
Allocators
  • Hide the memory model to improve portability
  • details of pointer types
  • the type of their difference
  • the size of objects
  • the memory allocation and deallocation primitives
  • STL has standard requirements for allocators
  • Objects that encapsulate the memory model.
  • STL containers have allocator parameters.

23
Adaptors
  • Template classes providing interface mappings.
  • Container adaptors
  • Restricted interfaces to containers
  • stack, queue, priority_queue built on different
    sequence types.
  • Iterator adaptors
  • Insert iterator
  • Will insert an item into position rather than
    overwriting
  • Reverse iterator
  • Traverse container backwards
  • Function adaptors
  • Create a Function Object from a pointer to a
    function
  • Convert 2-parameter function to 1-parameter
    function

24
Summary
  • Standard template library
  • Collection of containers common algorithms
  • Flexibility through templates
  • Designed for consistency with C style
  • E.g. iterators pointers
  • Use constraints as part of contract
  • STL Components
  • Container
  • Algorithm
  • Iterator
  • Function Objects
Write a Comment
User Comments (0)
About PowerShow.com