STL: C++ Standard Library

Similar documents
STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

STL Standard Template Library

Template based set of collection classes STL collection types (container types)

Chapter 5. The Standard Template Library.

SSE2034: System Software Experiment 3

use static size for this buffer

Standard Template Library

CS197c: Programming in C++

COEN244: Class & function templates

Templates and Vectors

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

PIC 10A. Lecture 23: Intro to STL containers

CS183 Software Design. Textbooks. Grading Criteria. CS183-Su02-Lecture 1 20 May by Eric A. Durant, Ph.D. 1

Programming in C++ using STL. Rex Jaeschke

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

CPSC 427a: Object-Oriented Programming

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.

Advanced C++ STL. Tony Wong

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

1. The term STL stands for?

CS11 Advanced C++ Fall Lecture 1

by Pearson Education, Inc. All Rights Reserved. 2

The Standard Template Library. An introduction

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

Exceptions, Templates, and the STL

2

Lecture-5. STL Containers & Iterators

General Advise: Don t reinvent the wheel

CS11 Advanced C++ Spring 2018 Lecture 2

Standard Library Reference

C++ 11 and the Standard Library: Containers, Iterators, Algorithms

Module 9. Templates & STL

This chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness.

VI. Templates A. Introduction.

Vector. Vector Class. class Vector { public: typedef unsigned int size_type;

Object-Oriented Programming

Chapter 17: Linked Lists

CSE 100: C++ TEMPLATES AND ITERATORS

CS 103 Unit 12 Slides

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

19.1 The Standard Template Library

pointers & references

Sequential Containers. Ali Malik

To know the relationships among containers, iterators, and algorithms ( 22.2).

Lectures 11,12. Online documentation & links

CSE 100: C++ TEMPLATES AND ITERATORS

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Intermediate Programming, Spring 2017*

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types

Function Templates. Consider the following function:

Containers in C++ and Java

Introducing C++ to Java Programmers

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

vector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second

CSI33 Data Structures

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation

Lectures 19, 20, 21. two valid iterators in [first, last) such that i precedes j, then *j is not less than *i.

Chapter 17: Linked Lists

Dynamic Data Structures

Computational Physics

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

Sequential Containers. Ali Malik

Unit 4 Basic Collections

CS2255 HOMEWORK #1 Fall 2012

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

Teaching with the STL

CSCE 110 PROGRAMMING FUNDAMENTALS

Vectors. CIS 15 : Spring 2007

CSC 222: Computer Programming II. Spring 2004

GridKa School 2013: Effective Analysis C++ Standard Template Library

Writing Generic Functions. Lecture 20 Hartmut Kaiser hkaiser/fall_2013/csc1254.html

Concurrent Data Structures in C++ CSInParallel Project

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

Programming with Haiku

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

the Stack stack ADT using the STL stack are parentheses balanced? algorithm uses a stack adapting the STL vector class adapting the STL list class

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Faculty of Information and Communication Technologies

List, Stack, and Queues

Exam 3 Chapters 7 & 9

CSE 100: C++ TEMPLATES AND ITERATORS

Exercise 6.2 A generic container class

I source_beg, source_end; // defines a range of values in a source container // defines the beginning of a range in a destination container

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Abstract Data Types 1

STL in Action: Helper Algorithms

G52CPP C++ Programming Lecture 18

AN OVERVIEW OF C++ 1

the Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Introduction to Programming using C++

Transcription:

STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1

We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms are commonly used, the C++ standard committee added the Standard Template Library (STL) to the C++ Standard Library. The STL defines powerful, template-based, reusable components that implement many common data structures and algorithms used to process those data structures. CSC 330 OO Software Design 2

Standard Template Library (STL) is a library of generic container classes which are both efficient and functional C++ STL developed in early 90's at Hewlett Packard Laboratories Alex Stepanov and Meng Lee became part of C++ standard in 1994 implementations available by late 90's CSC 330 OO Software Design 3

Main Ideas General purpose: generic data structures & algorithms, templates Flexibility: Allows for many combinations of algorithm-container Simple & uniform interface: interface through templates (not inheritence) Efficiency CSC 330 OO Software Design 4

STL components Containers templates for classes which hold a collection of elements Algorithms templates for functions which operate on a range of elements from a container range is specified by iterators Iterators give access to the elements in a container allow for movement from one element to another Container classes Iterators Algorithms CSC 330 OO Software Design 5

Components Containers: Each STL container has associated member functions. A subset of these member functions is defined in all STL containers. The containers are divided into three major categories sequence containers, associative containers and container adapters. Iterators: allow access into containers. They have properties similar to those of pointers, and are used by programs to manipulate the STL-container elements. Algorithms: STL algorithms are functions that perform such common data manipulations as searching, sorting and comparing elements (or entire containers). The STL provides approximately 70 algorithms. Most of them use iterators to access container elements. Each algorithm has minimum requirements for the types of iterators that can be used with it. CSC 330 OO Software Design 6

Containers CSC 330 OO Software Design 7

Basic Sequential Containers CSC 330 OO Software Design 8

STL Containers (part 1 of 2) CSC 330 OO Software Design 9

STL Containers (part 2 of 2) CSC 330 OO Software Design 10

STL Containers -Common Member Functions (Part 1 of 3) CSC 330 OO Software Design 11

STL Containers -Common Member Functions (Part 2 of 3) CSC 330 OO Software Design 12

STL Containers -Common Member Functions (Part 3 of 3) CSC 330 OO Software Design 13

STL Containers header files The header files for each of the Standard Library containers are shown below. CSC 330 OO Software Design 14

Containers typedefs The typedefs shown in the next two tables are used in generic declarations of variables, parameters to functions and return values from functions.for example, value_type in each container is always a typedef that represents the type of value stored in the container. The first-class containers are vectors, deques, lists, sets, multisets, maps and multimaps. CSC 330 OO Software Design 15

Containers typedefs (Part 1 of 2) CSC 330 OO Software Design 16

Containers typedefs (Part 2 of 2) CSC 330 OO Software Design 17

vector<t> growable, self-contained, type-independent array element type specified when a vector is declared vector<double> numbers; vector<cashier> checkoutstations; has a set of operations (methods) A vector changes size dynamically. A vector supports random-access. All STL algorithms can operate on a vector. Examples vector<int> v1; (capacity is 0) vector<float> v2 (10); (capacity is 10; size is 10) vector<string> v3 (5, "C++"); (capacity is 5; size is 5) CSC 330 OO Software Design 18

The Vector An enhancement of the array. Can be used like an array: Access a value via an index x = v[i]; v[j] = z; Additional capabilities: Increase or decrease its length Insert an element at a specified position Remove an element from a specified position CSC 330 OO Software Design 19

Vector Example // Create a vector to hold strings. vector<string> my_vector; // Add some entries. my_vector.push_back("bashful"); my_vector.push_back("awful"); my_vector.push_back("jumpy"); my_vector.push_back("happy"); CSC 330 OO Software Design 20

Vector Example (2) my_vector.insert(2, Doc ); Had to slide [2],[3] to [3],[4] CSC 330 OO Software Design 21

Vector Example (3) my_vector.push_back("dopey"); // add at end Cheap to add at end CSC 330 OO Software Design 22

size and capacity Functions with vector Container initially returns 0 for size and capacity of vector v. Function size available in every container returns the number of elements currently stored in the container. Function capacity returns the number of elements that can be stored in the vector before the vector needs to dynamically resize itself to accommodate more elements. CSC 330 OO Software Design 23

Some vector<t> methods V.capacity( ) //size of array currently allocated V.size( ) //number of values V contains V.empty( ) //true iff V.size( ) is 0 V.reserve(n) //grow V so its capacity is n V.push_back(val) //add val at end of V V.pop_back( ) //erase V's last element V[i] //access element of V whose index is i V.at(i) //access element of V whose index is i CSC 330 OO Software Design 24

#include <iostream> #include <vector> using namespace std; bool Search(const vector<int> & V, int item); int main ( ) { vector<int> numbers; int number; while (cin >> number) { // enter <control> D to stop the loop if (Search(numbers, number)) cout << "Duplicate" << endl; else numbers.push_back(number); } cout << "number of unique values: " << numbers.size( ); return 0; } bool Search(const vector<int> & V, int item) { int p = 0; while(p < V.size( ) ) if (item = = V[p]) // or V.at(p) return true; else p++; return false; } CSC 330 OO Software Design 25

list<t> class another STL container class used for storing a linear collection of like items comparison to a vector? linked list vs array is the underlying data structure no indexing (iterators are bidirectional) inserts and deletes anywhere are done in a constant amount of time CSC 330 OO Software Design 26

a list<t> data structure head ------ size 2 CSC 330 OO Software Design 27

Basic list class methods list( ); // construct an empty list list (const list<t> & alist); // copy constructor ~list( ); // destructor list<t> operator= (const list<t> & alist); // assignment operator bool empty( ); int size( ); CSC 330 OO Software Design 28

Some more list methods L.push_back(value) // append value to L L.push_front(value) // insert value at front of L L.insert(pos, value) // insert value into L at // position indicated by iterator pos L.front( ) // return L's first element L.back( ) // return L's last element L.begin( ) // return an iterator positioned at start L.end( ) // return the"past the end" iterator L.sort( ) // sort L's elements using < CSC 330 OO Software Design 29

#include <list> #include <iostream> using namespace std; int main ( ) { list<int>l; L.push_back (9); L.push_back (7); L.push_back (5); L.push_back (3); list<int>::iterator p; for (p = L.begin ( ); p!= L.end ( ); p++) cout << *p << endl; for (p = L.begin ( ); p!= L.end ( ); p++) (*p)++; for (p = L.begin ( ); p!= L.end ( ); p++) cout << *p << endl; return 0; } 9 7 5 3 10 8 6 4 Press any key to continue CSC 330 OO Software Design 30

list in C++ (STL) Syntax #include <list> using namespace std; list<t> collection; // T: datatype stored in vector CSC 330 OO Software Design 31

list Operations Adding elements push_back At the end push_front At the beginning insert Anywhere Removing an element pop_back From the end pop_front From the beginning erase, remove - Anywhere CSC 330 OO Software Design 32

list Operations (2) Information accessors/inspectors size How many? empty Are there none? Modification sort NOT part of <algorithm> reverse change the order CSC 330 OO Software Design 33

Member Functions CSC 330 OO Software Design 34

Member Functions of Sequential Container CSC 330 OO Software Design 35

Examples CSC 330 OO Software Design 36

STL Iterators Iterators have many features in common with pointers and are used to point to the elements of first-class containers (vectors, deques, lists, sets, multisets, maps and multimaps). Iterators hold state information sensitive to the particular containers on which they operate; thus, iterators are implemented appropriately for each type of container. Certain iterator operations are uniform across containers. For example, the dereferencing operator (*) dereferences an iterator so that you can use the element to which it points. The ++ operation on an iterator moves it to the next element of the container (much as incrementing a pointer into an array aims the pointer at the next element of the array). CSC 330 OO Software Design 37

STL Iterators cont d STL first-class containers provide member functions begin and end. Function begin returns an iterator pointing to the first element of the container. Function end returns an iterator pointing to the first element past the end of the container (an element that doesn t exist). CSC 330 OO Software Design 38

STL Iterators cont d If iterator i points to a particular element, then ++i points to the next element and *i refers to the element pointed to by i. The iterator resulting from end is typically used in an equality or inequality comparison to determine whether the moving iterator (i in this case) has reached the end of the container. An object of type iterator refers to a container element that can be modified. An object of type const_iterator refers to a container element that cannot be modified. CSC 330 OO Software Design 39

Iterator typedefs CSC 330 OO Software Design 40

Iterator Types CSC 330 OO Software Design 41

STL Iterators Iterators are allow to traverse sequences Methods operator* operator++, and operator Different types of iterators - to support read, write and random access Containers define their own iterator types Changing the container can invalidate the iterator CSC 330 OO Software Design 42

STL iterators iterators are "pointer-like" objects provide a generic way to access the elements of any container class many STL algorithms require iterators as arguments some STL algorithms return an iterator each STL container class has an iterator class associated with it vector<t>::iterator list<t>::iterator stack<t> and queue<t> don't have iterators CSC 330 OO Software Design 43

Iterators cont d CSC 330 OO Software Design 44

Instantiating STL Container CSC 330 OO Software Design 45

Iterators CSC 330 OO Software Design 46

Iterator Types Output Input Forward Bi-directional Random Read x = *i x = *i x = *i x = *i Write *i = x *i = x *i = x *i = x Iteration ++ ++ ++ ++, -- ++, --, +, -, +=, -= Comparison ==,!= ==,!= ==,!= ==,!=, <, >, <=, >= Output: write only and can write only once Input: read many times each item Forward supports both read and write Bi-directional support also decrement Random supports random access (just like C pointer) CSC 330 OO Software Design 47

Data Access CSC 330 OO Software Design 48

Data Insertion CSC 330 OO Software Design 49

Constant Iterators CSC 330 OO Software Design 50

Example CSC 330 OO Software Design 51

STL Algorithms An algorithm is an operation (function) that can be applied to many STL containers The STL algorithms are generic - they can operate on a variety of data structures. STL container classes such as vector and list Program-defined data structures Behavior must satisfy the requirements of a particular algorithm STL algorithms achieve generality by accessing and traversing the elements of a container indirectly through iterators. Iterators must be settable and dereferencable CSC 330 OO Software Design 52

Sort Algorithm The sort algorithm is an operation (function) that can be applied to many STL containers notable exception: list container (has it s own method) sort() orders a container's contents in ascending order as defined by the operator<() as applied to the container s elements Programmer-defined types can be sorted just as easily as a built-in type CSC 330 OO Software Design 53

find Algorithm searches a subrange of the elements in a container (or all the elements), looks for an element that is "equal to" a specified value; stops when it finds the first element equal to the specified value the equality operator (==) must be defined for the type of the container's elements. search value must be of the same type as the elements stored in the container or of a type that the compiler can automatically convert. Return value is an iterator specifying the position of the first matching element. If no matching element is found, the return value is equal to the iterator specifying the end of the element subrange CSC 330 OO Software Design 54

CSC 330 OO Software Design 55

Algorithms cont d CSC 330 OO Software Design 56

STL Algorithms are function templates designed to operate on a sequence of elements rather than methods the sequence is designated by two iterators most container classes have the following two methods begin( ) - returns an iterator positioned at the container's first element end( ) - returns an iterator positioned past the container's last element (past-the-end) c.begin( ), c.end( ) specifies a sequence which contains all elements of the container c CSC 330 OO Software Design 57

Algorithms Most STL algorithms works on sequences Sequences are passed as two iterators: beginning element element one after last p q sequence [p,q) Algorithms depend on iterator type not on container type CSC 330 OO Software Design 58

Algorithms cont d CSC 330 OO Software Design 59

Algorithms cont d CSC 330 OO Software Design 60

Using sort( ) CSC 330 OO Software Design 61

Using sort( ) cont d CSC 330 OO Software Design 62

for_each( ( ) algorithm CSC 330 OO Software Design 63

Iterators and Algorithms CSC 330 OO Software Design 64

More Iterators CSC 330 OO Software Design 65

Discussions CSC 330 OO Software Design 66

Container Adaptor CSC 330 OO Software Design 67