Title: C Programming: Program Design Including Data Structures, Fourth Edition
1C Programming Program Design Including Data
Structures, Fourth Edition
- Chapter 22
Standard Template Library (STL)
2Objectives
- In this chapter, you will
- Learn about the Standard Template Library (STL)
- Become familiar with the basic components of the
STL containers, iterators, and algorithms - Explore how various containers are used to
manipulate data in a program - Discover the use of iterators
- Learn about various generic algorithms
3Introduction
- ANSI/ISO Standard C is equipped with a Standard
Template Library (STL) - The STL provides class templates to process
lists, stacks, and queues - This chapter discusses many important features of
the STL and shows how to use its tools
4Components of the STL
- Components of the STL
- Containers ( sequence, associative, adapters )
- Iterators
- Algorithms
- Containers and iterators are class templates
- Iterators are used to step through the elements
of a container ( iterators are pointers ) - Algorithms are used to manipulate data
5Container Types
- Containers are used to manage objects of a given
type - Three categories
- Sequence containers ( aka sequential)
- Associative containers
- Container adapters
6Sequence Containers
- Every object has a specific position ( index )
- Three predefined sequence containers
- vector - dynamic array
- deque - double-ended queue (pronounced deck)
- dynamic arrays that allow elements to be
inserted at both ends. - list - doubly-linked list
- not a random access structure
7Sequence Container vector
- Stores and manages its objects in a dynamic array
- include ltvectorgt
- To define an object of type vector, we must
specify the type of the object - Examples
- vectorltintgt intList
- vectorltstringgt stringList
- vector contains several constructors
- Recall that
- ( ) are not required when creating an object if
a default constructor exists. - new operator is only used in C to dynamically
allocate memory.
8(No Transcript)
9Sequence Container vector (continued)
- Basic vector operations
- Item insertion and deletion
- Stepping through the elements
10(No Transcript)
11Sequence Container vector (continued)
12(No Transcript)
13(No Transcript)
14Declaring an Iterator to a Vector Container
- A vector contains a typedef iterator
- For example, the statement
- vectorltintgtiterator intVecIter
- declares intVecIter to be an iterator into a
vector container of type int - intVecIter advances the iterator to the next
element in the container - intVecIter returns the element at the current
iterator position - An iterator is a pointer
15Containers and the Functions begin and end
- Every container contains the member function
begin and end - begin returns a pointer to the first element
address of first element - end returns a pointer to the last element
address of last element - These functions do not have any parameters
- The example below steps through a vector using an
interator ( a pointer ).
use lt
16Member Functions Common to All Containers
17(No Transcript)
18Member Functions Common to All Containers
(continued)
19Member Functions Common to Sequence Containers
20Member Functions Common to Sequence Containers
(continued)
21The copy Algorithm
- Function copy
- convenient way to output the elements of a
container - Copies elements from one place to another
- can output the elements of a vector
- Prototype copies elements within range
first1...last-1 - include ltalgorithmgt
22The copy Algorithm (continued)
- Example
- int intArray 5, 6, 8, 3, 40, 36, 98, 29,
75 - vectorltintgt vecList(9)
- copy(intArray, intArray 9, vecList.begin())
-
- After the previous statement executes
- vecList 5, 6, 8, 3, 40, 36, 98, 29, 75
- An array name is a constant pointer
include ltalgorithmgt
first last (pointer is past the
end of the array)
23The copy Algorithm (continued)
- Consider the statements
- int intArray 5, 6, 8, 3, 40, 36, 98, 29,
75 - copy(intArray 1, intArray 9, intArray)
- After the previous statement executes
- intArray 6, 8, 3, 40, 36, 98, 29, 75, 75
- Now, consider the statement
- copy(vecList.rbegin() 2, vecList.rend(),
vecList.rbegin()) - After the previous statement executes
- vecList 5, 6, 5, 6, 8, 3, 40, 36, 98
24The ostream Iterator and the Function copy
- One way to output the contents of a container is
to use a for loop, along with begin (initialize)
and end (loop limit) - copy can output a container
- An iterator of the type ostream specifies
destination - When you create an iterator of the type ostream,
specify the type of element that the iterator
will output
25The ostream Iterator and the Function copy
(continued)
- Example
- ostream_iteratorltintgt screen(cout, " ")
- copy(intArray, intArray 9, screen)
- copy(vecList.begin(), vecList.end(), screen)
- The last statement is equivalent to
- copy(vecList.begin(), vecList.end(),
ostream_iteratorltintgt(cout, " ")) - Another example
- copy(vecList.begin(), vecList.end(),
ostream_iteratorltintgt(cout, ", "))
26Sequence Container deque
- deque stands for double ended queue
- Implemented as dynamic arrays
- Elements can be inserted at both ends
- A deque can expand in either direction
- Elements can also be inserted in the middle
27(No Transcript)
28(No Transcript)
29Sequence Container list
- Lists are implemented as doubly linked lists
- Every element in a list points to both its
immediate predecessor and its immediate successor
(except the first and last element) - A list is not a random access data structure
30(No Transcript)
31(No Transcript)
32(No Transcript)
33(No Transcript)
34Sequence Container list (continued)
35Iterator ( an object ) works like an intelligent
pointer
- An iterator points to the elements of a container
(sequence or associative) - Iterators provide access to each element
- The most common operations on iterators are
- (increment)
- (dereference)
36Types of Iterators
- Input
- have read access step forward element-by-element
- Output
- have write access step forward
element-by-element - Forward
- have all functionality of input and almost all of
output iterators - Bidirectional
- can go forward and backward
- Random access
- bidirectional iterators that can randomly process
the elements of a container
37Types of Iterators (continued)
38Input Iterators
39Output Iterators
- Output iterators cannot be used to iterate over a
range twice - If we write data at same position, there is no
guarantee that new value will replace old one
40Forward Iterators
41Bidirectional Iterators
- Forward iterators that can also iterate backward
over the elements - The operations defined for forward iterators
apply to bidirectional iterators - Use the decrement operator to step backward
42Random Access Iterators
- Can be used with containers of the types vector,
deque, string, as well as arrays - Operations defined for bidirectional iterators
apply to random access iterators
43(No Transcript)
44Types of Iterators (continued)
45typedef iterator
- Every container contains a typedef iterator
- The statement
- vectorltintgtiterator intVecIter
- declares intVecIter to be an iterator into a
vector container of the type int
46typedef const_iterator
- With the help of an iterator into a container and
the dereference operator, , you can modify the
elements of the container - If the container is declared const, then we must
prevent the iterator from modifying the elements - Every container contains typedef
const_iterator to handle these situations
47typedef reverse_iterator
- Every container also contains the
- typedef reverse_iterator
- An iterator of this type is used to iterate
through the elements of a container in reverse
48typedef const_reverse_iterator
- An iterator of this type is a read-only iterator
and is used to iterate through the elements of a
container in reverse - Required if the container is declared as const,
and we need to iterate through the elements of
the container in reverse
49Other typedefs Common to All Containers
50Stream Iterators
- istream_iterator
- Used to input data into a program from an input
stream - ostream_iterator
- Used to output data into an output stream
51Associative Containers
- Elements in an associative container are
automatically sorted according to some ordering
criteria (ascending / descending) - The predefined associative containers in the STL
are - Set
- Multiset
- Map
- Multimap
- map and multimap provide operations for
manipulation of values associated with a key (aka
mapped values) - key/value pairs
- one-to-one mapping of key to value
- a multimap allows duplicate keys with associated
values - a map is also called an associative array
52Associative Containers set and multiset
- Associative containers set and multiset
automatically sort their elements - class set
- class multiset
- multiset allows duplicates set does not
- The default sorting criterion is the relational
operator lt - Ascending sequence
- For user-defined data types, such as classes, the
relational operators must be overloaded properly - include ltsetgt
53Declaring set or multiset Associative Containers
ctType is set or multiset
54(No Transcript)
55Declaring set or multiset Associative Containers
(continued)
- To use sort criteria other than the default,
specify this option when declaring container - In the statements in Lines 2 and 4, note the
space between the two gt symbols - This space is important because gtgt is a shift
operator in C
56Item Insertion and Deletion from set/multiset
57Item Insertion and Deletion from set/multiset
(continued)
58Container Adapters
- The STL provides containers to accommodate
special situations called container adapters - The three container adapters are
- Stacks LIFO
- Queues FIFO (aka FCFS)
- Priority Queues
- allows insertions in sorted order and deletions
from the front of the queue - Container adapters do not support any type of
iterator
59Stack
- The STL provides a stack class
60Queue
61Containers, Associated Header Files, and Iterator
Support
- The previous sections discussed various types of
containers - Recall that every container is a class
- The definition of the class implementing a
specific container is contained in the header
file - Table 22-21 describes the container, its
associated header file, and the type of iterator
supported by the container
62(No Transcript)
63Algorithms
- Several operations can be defined for a
container - Some of the operations are very specific to a
container and are provided as part of the
container definition - Other operations are common to all containers
- The generic algorithms are contained in the
header file algorithm
64STL Algorithm Classification
- Operations such as find, sort, and merge are
common to all containers and are provided as
generic algorithms - STL algorithms can be classified as follows
- Nonmodifying algorithms
- Modifying algorithms
- Numeric algorithms
- Heap algorithms
65Non-modifying Algorithms
- Nonmodifying algorithms do not modify the
elements of the container
66(No Transcript)
67Numeric Algorithms
- Numeric algorithms perform numeric calculations
on the elements of a container
68Heap Algorithms
- Heap sort algorithm sorts array data
- The array containing the data is viewed as a
binary tree
69Function Objects
- To make a generic algorithm flexible, the STL
usually provides two forms - Use the natural operation to accomplish the goal
- Specify criteria based on which algorithm
processes the elements - Example adjacent_find searches and returns
position of first two equal elements - Alternatively, we can specify criteria (say, less
than) to look for the first two elements
70Function Objects (continued)
- Function object
- contains a function that can be treated as such
using the operator() function call opertor - In fact, a function object is a class template
that overloads the function call operator - In addition to allowing you to create your own
function objects, the STL provides arithmetic,
relational, and logical function objects - The STLs function objects are contained in the
header file functional
71(No Transcript)
72(No Transcript)
73Function Objects (continued)
74Function Objects (continued)
- The STL relational function objects can also be
applied to containers - Example
- vecList 2, 3, 4, 5, 1, 7, 8, 9
- To see if the elements are out of order
- intItr adjacent_find(vecList.begin(),
vecList.end(), greaterltintgt()) - The function returns a pointer to element 5,
which is stored in intItr
75Function Objects (continued)
76Predicates
- Predicates are special types of function objects
that return Boolean values - Typical use specify searching/sorting criteria
- Two types
- Unary check a property for a single argument
- Binary check a specific property for a pair
- In the STL, a predicate must always return the
same result for the same value - Functions that modify their internal states
cannot be considered predicates
77Insert Iterator
- back_inserter
- uses push_back in place of operator the
argument is the container - copy(list, list 5, back_inserter(vList))
- front_inserter
- uses push_front argument is the container
itself - Cannot be used for the vector container
- inserter
- uses insert
- Two arguments the container and an iterator to
the container specifying the position at which
the insertion should begin
78STL Algorithms
- STL algorithms include documentation with the
function prototypes - The parameter types indicate for which type of
container the algorithm is applicable
79The Functions fill and fill_n
- fill
- fills a container with elements
- fill_n
- fills in the next n elements
- The element that is used as a filling element is
passed as a parameter - Defined in header file algorithm
- Prototypes
80The Functions generate and generate_n
- Used to generate elements and fill a sequence
- Defined in header file algorithm
- Prototypes
81The Functions find, find_if, find_end, and
find_first_of
82The Functions remove, remove_if, remove_copy,
remove_copy_if
- remove
- removes certain elements from a sequence
- remove_if
- removes elements from a sequence by using some
criteria
83The Functions replace, replace_if, replace_copy,
replace_copy_if
84The Functions swap, iter_swap, and swap_ranges
- Swaps elements
- Defined in header file algorithm
- Prototypes
85The Functions search, search_n, sort, and
binary_search
- Searches for and sorts elements
86The Function adjacent_find
- adjacent_find finds the first occurrence of
consecutive elements that meet criteria
87The Function merge
- merge merges the sorted lists
- The lists must be sorted using same criteria
88The Function inplace_merge
- inplace_merge combines sorted sequences
89reverse, reverse_copy, rotate, and rotate_copy
- reverse
- reverses the order of the elements in a given
range - reverse_copy
- reverses the elements of a given range while
copying into a destination range the source is
not modified - rotate
- rotates the elements of a given range
- rotate_copy
- combination of rotate and copy elements of the
source are copied at the destination in a rotated
order - The source is not modified
90reverse, reverse_copy, rotate, and rotate_copy
91count, count_if, max, and min
- count
- counts the occurrence of a given item in a given
range returns the number of times the value
specified by the parameter occurs - count_if
- counts occurrences of a given value in a given
range satisfying a certain criterion - min
- determines the minimum of two values
- max
- determines the maximum of two values
92max_element, min_element, and random_shuffle
- max_element
- determines the largest element in a given range
- min_element
- determines the smallest element in a given range
- random_shuffle
- randomly orders elements
93(No Transcript)
94The Function for_each
- for_each
- accesses and processes each element in a given
range by applying a function - Prototype
95The Function transform
- transform
- creates a sequence of elements at the destination
by applying the unary operation to each element
in the range
96Set Theory Operations
97(No Transcript)
98Numeric Algorithms
99Numeric Algorithms (continued)
100Summary
- STL consists of
- Containers
- class templates
- Iterators
- step through the elements of a container
- Algorithms
- manipulate the elements in a container
101Summary (continued)
- Containers
- Sequence
- vector, deque, and list
- Associative
- sets, multisets, maps, and multimaps
- Container adapters
- stacks, queues, and priority queues
102Summary (continued)
- Iterators
- input, output, forward, bidirectional, and random
access iterator - Predicates
- Boolean function objects
- Algorithms
- nonmodifying, modifying, numerical, and heap
- Algorithms are overloaded for flexibility