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

Slides:



Advertisements
Similar presentations
M The University Of Michigan Andrew M. Morgan EECS Lecture 22 Savitch Ch. 16 Intro To Standard Template Library STL Container Classes STL Iterators.
Advertisements

SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Data Structures Using C++ 2E
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
Mutating Algorithms All the algorithms we have seen have not modified the containers Some algorithms do modify values They do not modify iterators, only.
Chapter 14: Overloading and Templates
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
Data Structures Using C++ 2E
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
Data Structures Using C++ 2E
1 CSC 262 Programming in C++ II Sykes Day 18.  We’ve repeatedly emphasized the importance of software reuse.  Recognizing that many data structures.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
11 COS220 Concepts of PLs AUBG, COS dept Lecture 36 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++, Lafore, Chap 15 STL,
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overview 18.1 Iterators 18.2 Containers 18.3 Generic Algorithms Slide
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
C++ STL CSCI 3110.
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Data Structures Using C++1 Chapter 4 Standard Template Library (STL)
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
1 Iterators Good reference site:
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
Chapter 22 STL Containers §22.1 STL Basics §22.2 STL Iterators §22.3 Sequence Containers §22.4 Associative Containers §22.5 Container Adapters.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
CS 403: Programming Languages Lecture 24 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Intro to the C++ STL Timmie Smith September 6, 2001.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
The Standard Template Library Container Classes Version 1.0.
Standard Template Library (STL) - Use Vector and Deque
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
C++ Review STL CONTAINERS.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 17: Linked Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 18: Linked Lists.
Introduction to Templates and Standard Template Library 1.
Object-Oriented Programming (OOP) Lecture No. 42.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
CS212: Object Oriented Analysis and Design
C++ Programming:. Program Design Including
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 22: Standard Template Library (STL)
CS212: Object Oriented Analysis and Design
Standard Template Library
Standard Template Library
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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 <

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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