Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)

Similar presentations


Presentation on theme: "C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)"— Presentation transcript:

1 C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)

2 Objectives 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 C++ Programming: Program Design Including Data Structures, Fourth Edition2

3 Introduction 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 C++ Programming: Program Design Including Data Structures, Fourth Edition3

4 Components 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 C++ Programming: Program Design Including Data Structures, Fourth Edition4

5 Container Types Containers are used to manage objects of a given type Three categories: −Sequence containers ( aka sequential) −Associative containers −Container adapters C++ Programming: Program Design Including Data Structures, Fourth Edition5

6 Sequence 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 C++ Programming: Program Design Including Data Structures, Fourth Edition6

7 Sequence Container: vector Stores and manages its objects in a dynamic array #include To define an object of type vector, we must specify the type of the object −Examples: vector intList; vector 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. C++ Programming: Program Design Including Data Structures, Fourth Edition7

8

9 Sequence Container: vector (continued) Basic vector operations: −Item insertion and deletion −Stepping through the elements C++ Programming: Program Design Including Data Structures, Fourth Edition9

10

11 Sequence Container: vector (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition11

12

13

14 Declaring an Iterator to a Vector Container A vector contains a typedef iterator For example, the statement vector ::iterator 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 C++ Programming: Program Design Including Data Structures, Fourth Edition14

15 Containers 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 ). C++ Programming: Program Design Including Data Structures, Fourth Edition15 use <

16 Member Functions Common to All Containers C++ Programming: Program Design Including Data Structures, Fourth Edition16

17

18 Member Functions Common to All Containers (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition18

19 Member Functions Common to Sequence Containers C++ Programming: Program Design Including Data Structures, Fourth Edition19

20 Member Functions Common to Sequence Containers (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition20

21 The 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 C++ Programming: Program Design Including Data Structures, Fourth Edition21

22 The copy Algorithm (continued) Example: int intArray[] = {5, 6, 8, 3, 40, 36, 98, 29, 75}; vector 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 C++ Programming: Program Design Including Data Structures, Fourth Edition22 first last (pointer is past the end of the array) #include

23 The 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} C++ Programming: Program Design Including Data Structures, Fourth Edition23

24 The 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 C++ Programming: Program Design Including Data Structures, Fourth Edition24

25 The ostream Iterator and the Function copy (continued) Example: ostream_iterator 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_iterator (cout, " ")); Another example: copy(vecList.begin(), vecList.end(), ostream_iterator (cout, ", ")); C++ Programming: Program Design Including Data Structures, Fourth Edition25

26 Sequence 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 C++ Programming: Program Design Including Data Structures, Fourth Edition26

27

28

29 Sequence 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 C++ Programming: Program Design Including Data Structures, Fourth Edition29

30

31

32

33

34 Sequence Container: list (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition34

35 Iterator ( 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) C++ Programming: Program Design Including Data Structures, Fourth Edition35

36 Types 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 C++ Programming: Program Design Including Data Structures, Fourth Edition36

37 Types of Iterators (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition37

38 Input Iterators C++ Programming: Program Design Including Data Structures, Fourth Edition38

39 Output 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 C++ Programming: Program Design Including Data Structures, Fourth Edition39

40 Forward Iterators C++ Programming: Program Design Including Data Structures, Fourth Edition40

41 Bidirectional 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 C++ Programming: Program Design Including Data Structures, Fourth Edition41

42 Random 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 C++ Programming: Program Design Including Data Structures, Fourth Edition42

43

44 Types of Iterators (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition44

45 typedef iterator Every container contains a typedef iterator The statement: vector ::iterator intVecIter; declares intVecIter to be an iterator into a vector container of the type int C++ Programming: Program Design Including Data Structures, Fourth Edition45

46 typedef 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 C++ Programming: Program Design Including Data Structures, Fourth Edition46

47 typedef 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 C++ Programming: Program Design Including Data Structures, Fourth Edition47

48 typedef 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 C++ Programming: Program Design Including Data Structures, Fourth Edition48

49 Other typedef s Common to All Containers C++ Programming: Program Design Including Data Structures, Fourth Edition49

50 Stream Iterators istream_iterator −Used to input data into a program from an input stream ostream_iterator −Used to output data into an output stream C++ Programming: Program Design Including Data Structures, Fourth Edition50

51 Associative 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 C++ Programming: Program Design Including Data Structures, Fourth Edition51 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

52 Associative 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 < [ Ascending sequence ] For user-defined data types, such as classes, the relational operators must be overloaded properly #include C++ Programming: Program Design Including Data Structures, Fourth Edition52

53 Declaring set or multiset Associative Containers C++ Programming: Program Design Including Data Structures, Fourth Edition53 ctType is set or multiset

54

55 Declaring 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 > symbols −This space is important because >> is a shift operator in C++ C++ Programming: Program Design Including Data Structures, Fourth Edition55

56 Item Insertion and Deletion from set/multiset C++ Programming: Program Design Including Data Structures, Fourth Edition56

57 Item Insertion and Deletion from set/multiset (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition57

58 Container Adapters The STL provides containers to accommodate special situations called container adapters The three container adapters are: −StacksLIFO −QueuesFIFO (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 C++ Programming: Program Design Including Data Structures, Fourth Edition58

59 Stack The STL provides a stack class C++ Programming: Program Design Including Data Structures, Fourth Edition59

60 Queue C++ Programming: Program Design Including Data Structures, Fourth Edition60

61 Containers, 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 C++ Programming: Program Design Including Data Structures, Fourth Edition61

62

63 Algorithms 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 C++ Programming: Program Design Including Data Structures, Fourth Edition63

64 STL 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 C++ Programming: Program Design Including Data Structures, Fourth Edition64

65 Non-modifying Algorithms Nonmodifying algorithms do not modify the elements of the container C++ Programming: Program Design Including Data Structures, Fourth Edition65

66

67 Numeric Algorithms Numeric algorithms perform numeric calculations on the elements of a container C++ Programming: Program Design Including Data Structures, Fourth Edition67

68 Heap Algorithms Heap sort algorithm sorts array data The array containing the data is viewed as a binary tree C++ Programming: Program Design Including Data Structures, Fourth Edition68

69 Function 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 C++ Programming: Program Design Including Data Structures, Fourth Edition69

70 Function 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 STL’s function objects are contained in the header file functional C++ Programming: Program Design Including Data Structures, Fourth Edition70

71

72

73 Function Objects (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition73

74 Function 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(), greater ()); The function returns a pointer to element 5, which is stored in intItr C++ Programming: Program Design Including Data Structures, Fourth Edition74

75 Function Objects (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition75

76 Predicates 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 C++ Programming: Program Design Including Data Structures, Fourth Edition76

77 Insert 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 C++ Programming: Program Design Including Data Structures, Fourth Edition77

78 STL Algorithms STL algorithms include documentation with the function prototypes The parameter types indicate for which type of container the algorithm is applicable C++ Programming: Program Design Including Data Structures, Fourth Edition78

79 The 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: C++ Programming: Program Design Including Data Structures, Fourth Edition79

80 The Functions generate and generate_n Used to generate elements and fill a sequence Defined in header file algorithm Prototypes: C++ Programming: Program Design Including Data Structures, Fourth Edition80

81 The Functions find, find_if, find_end, and find_first_of C++ Programming: Program Design Including Data Structures, Fourth Edition81

82 The 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 C++ Programming: Program Design Including Data Structures, Fourth Edition82

83 The Functions replace, replace_if, replace_copy, replace_copy_if C++ Programming: Program Design Including Data Structures, Fourth Edition83

84 The Functions swap, iter_swap, and swap_ranges Swaps elements Defined in header file algorithm Prototypes: C++ Programming: Program Design Including Data Structures, Fourth Edition84

85 The Functions search, search_n, sort, and binary_search Searches for and sorts elements C++ Programming: Program Design Including Data Structures, Fourth Edition85

86 The Function adjacent_find adjacent_find : finds the first occurrence of consecutive elements that meet criteria C++ Programming: Program Design Including Data Structures, Fourth Edition86

87 The Function merge merge : merges the sorted lists −The lists must be sorted using same criteria C++ Programming: Program Design Including Data Structures, Fourth Edition87

88 The Function inplace_merge inplace_merge : combines sorted sequences C++ Programming: Program Design Including Data Structures, Fourth Edition88

89 reverse, 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 C++ Programming: Program Design Including Data Structures, Fourth Edition89

90 reverse, reverse_copy, rotate, and rotate_copy C++ Programming: Program Design Including Data Structures, Fourth Edition90

91 count, 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 C++ Programming: Program Design Including Data Structures, Fourth Edition91

92 max_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 C++ Programming: Program Design Including Data Structures, Fourth Edition92

93

94 The Function for_each for_each : −accesses and processes each element in a given range by applying a function Prototype: C++ Programming: Program Design Including Data Structures, Fourth Edition94

95 The Function transform transform : −creates a sequence of elements at the destination by applying the unary operation to each element in the range C++ Programming: Program Design Including Data Structures, Fourth Edition95

96 Set Theory Operations C++ Programming: Program Design Including Data Structures, Fourth Edition96

97

98 Numeric Algorithms C++ Programming: Program Design Including Data Structures, Fourth Edition98

99 Numeric Algorithms (continued) C++ Programming: Program Design Including Data Structures, Fourth Edition99

100 Summary STL consists of: −Containers: class templates −Iterators: step through the elements of a container −Algorithms: manipulate the elements in a container C++ Programming: Program Design Including Data Structures, Fourth Edition100

101 Summary (continued) Containers −Sequence: vector, deque, and list −Associative: sets, multisets, maps, and multimaps −Container adapters: stacks, queues, and priority queues C++ Programming: Program Design Including Data Structures, Fourth Edition101

102 Summary (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 C++ Programming: Program Design Including Data Structures, Fourth Edition102


Download ppt "C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)"

Similar presentations


Ads by Google