©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Intro to the C++ Std Library.

Slides:



Advertisements
Similar presentations
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Advertisements

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,
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
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.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Generic programming starts with algorithms. Lift Minimal requirements: works with maximal family of types Concrete algorithm: requires specific data type.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
Templates and the STL.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Templates and Polymorphism Generic functions and classes
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
STL Algorithms algorithms independent of containers.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)‏
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++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
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.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 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.
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
Intro to the C++ STL Timmie Smith September 6, 2001.
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.
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.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Introduction to Templates and Standard Template Library 1.
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.
CS212: Object Oriented Analysis and Design
Introduction to C++ Systems Programming.
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library (STL)
Starting Out with C++ Early Objects Eighth Edition
Chapter 22: Standard Template Library (STL)
CS212: Object Oriented Analysis and Design
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
Containers, Iterators, Algorithms, Thrust
Class string and String Stream Processing
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library
Standard Template Library
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Standard Template Library
Presentation transcript:

©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Intro to the C++ Std Library

©Fraser Hutchinson & Cliff Green Major Components STL subset – containers, algorithms, iterators, function objects Strings – regular and wide char Numerics – complex type, valarray Streams – iostream, stream buffer Internationalization – locales, facets Utilities – auto_ptr, pair, numeric limits, min / max, allocators, bitset

©Fraser Hutchinson & Cliff Green Standard Template Library Subset of the C++ library comprised of containers, algorithms, iterators, and function objects Algorithms operate on ranges of elements, typically within a container or stream Iterators provide the “glue” and abstraction layer between containers and algorithms Function objects allow algorithms and certain containers to be highly customizable

©Fraser Hutchinson & Cliff Green STL Part of the ANSI / ISO C++ standard Created by Stepanov and Lee (originally at HP) Platform and compiler independent Avoid reinventing the wheel - STL provides type- safe implementations of –Many popular data structures as containers –Many popular algorithms to process the data in those containers STL is flexible, tested, debugged, and robust!

©Fraser Hutchinson & Cliff Green STL STL is extensible and customizable without inheritance STL abstraction does not mean inefficiency –Much of STL is implemented as inline –Pointers in containers are type-safe but share instantiation, saving code space

©Fraser Hutchinson & Cliff Green Std Lib Headers All are wrapped in the standard namespace, std #include // C++ string facilities #include // iostream facilities #include // istream class #include // ostream class #include // stream manipulators #include // ifstream, ofstream facilities #include // stringstream facilities #include // exception handling classes

©Fraser Hutchinson & Cliff Green Std Lib Headers (cont) #include // C++ complex class #include // numeric and type limits #include // C++ locale facilities #include // allocator and auto_ptr #include // pair class, relational ops #include // bit manipulation class #include // RTTI facilities #include // ‘new’ operator overloading #include // high performance arrays (STL headers are listed later)

©Fraser Hutchinson & Cliff Green Simple Input and Output std::cout - global object of type std::ostream for output streaming std::ostream - class that defines output (insertion operator) for all built-in and library types std::cin - global object of type std::istream for input streaming std::istream – class that defines input (extraction operator) for all built-in and library types

©Fraser Hutchinson & Cliff Green Ye Olde Example When using the standard library, every access must be either explicitly qualified with std or by using the using-directive or using-declaration. #include #include using std::cout; using std::endl; int main() { std::string const hi ("Hello world“); cout << hi << endl; return 0; }

©Fraser Hutchinson & Cliff Green Backwards Compatibility Standard headers in the form –Pre-standard C++ headers have.h extension (e.g. iostream.h). Use only if backwards compatibility is a requirement. C library headers have standard C++ versions, renamed by prepending a ‘c’ – is now

©Fraser Hutchinson & Cliff Green Differences in C Lib Headers The traditional C library functions are not all const-correct: –#include // C lib string facilities char * strchr(const char *ptr, int c); –return value points to position in ptr, and has been replaced with –#include // now in std namespace const char * strchr(const char *ptr, int c);

©Fraser Hutchinson & Cliff Green The String Class header defines std::string, a string class with a rich set of string construction, concatenation, searching, and substring methods ‘C’ string interface mechanisms (zero terminated character arrays) are provided String objects more convenient, flexible, safer (string logic is encapsulated within the class), and potentially more efficient than C strings, depending on usage

©Fraser Hutchinson & Cliff Green String Class Usage Considerations A given string implementation may not always be the best solution for your needs. There are tradeoffs between time and space, storage approaches, sharing mechanisms, copying strategies, and thread safety. –We need to have a certain amount of knowledge of an implementation.

©Fraser Hutchinson & Cliff Green Details Std library header actually defines a template class named std::basic_string std::string declaration is a typedef which instantiates std::basic_string with standard parameters for traditional char -based strings No restriction on what can be stored in a string – in particular, binary 0’s can be stored and will not be interpreted as the end of string

©Fraser Hutchinson & Cliff Green Accessing the C String in std::string has the member c_str(), returns a const pointer to a zero terminated array of chars; a non-zero terminated character pointer is returned by the data() method. // appropriate includes and using declarations int main() { string my_string (“Bubba”); char const * c_string (my_string.c_str()); cout << c_string << endl; }

©Fraser Hutchinson & Cliff Green C and C++ String Differences In C++, a quoted string literal is an array of characters, of type char const * Many functions take a string by const reference: int f (std::string const &); If a string literal is passed in, an implicit construction will occur: int x = f (“howdy”); // create string from const char* Standard C++ does not allow binding reference to unnamed temporary (older compilers may allow): int f (std::string &); // error if called with f(“howdy”);

©Fraser Hutchinson & Cliff Green Containers Typed collections of objects Provides type-safe implementations of common data structures: –linked list, array, stack, associative array, etc Algorithms are included to operate on the data in the containers: –sort, find, etc Uniform interface for all containers std::string is a special form of a sequence container (similar to vector )

©Fraser Hutchinson & Cliff Green Container Categories Sequence containers –vector#include –deque#include –list#include Associative containers –set, multiset#include –map, multimap#include Adapter containers –stack#include –queue, priority_queue#include

©Fraser Hutchinson & Cliff Green Data Structure Aspects, Sequences vector -rapid insertions/deletions at back, direct access with index list -rapid insertions/deletions anywhere, no direct access with index deque -direct access, rapid insertions at back/front stack -LIFO queue -FIFO

©Fraser Hutchinson & Cliff Green Data Structure Aspects, Associatives set -rapid lookup, no duplicates, stored in order multiset -same as set, duplicates OK map -1-to-1 mapping, key-based lookup, no duplicates, stored in order multimap -same as map, duplicates OK

©Fraser Hutchinson & Cliff Green Common Member Functions empty true if there are no members sizenumber of elements swapswaps elements of two containers begin, endforward iterator first, last element rbegin, rend reverse iterator first, last element

©Fraser Hutchinson & Cliff Green Common Member Functions operator=assign one container to another operator==compare two containers (if sizes same, compare each element) erase,clear erase or clear 1 or more elements

©Fraser Hutchinson & Cliff Green Ranges begin() refers to the first element. end() refers to the next position after the last element. [begin,end) –includes begin –excludes end –the number of elements is (end-begin) –an array of N elements is [A,A+N) –represent empty containers as [A,A)

©Fraser Hutchinson & Cliff Green Iterators Iterators are used to point to the elements of containers. Operators supported by iterators of all types –equality, inequality (p1=p2), (p1!=p2) –operator++ (increment) –operator* (dereference) In the implementation of STL, elements of containers are accessed only through iterators. Iterators are modeled on and share many concepts with pointers.

©Fraser Hutchinson & Cliff Green Input, Output, Forward Iterators Input iterators –can be used to read the elements of a container –used in algorithms: find(), accumulate(), equal() Output iterator –can be used to write the elements of a container –copy() takes an output iterator as its third argument Forward iterators –can read from or write to a container in one direction –used in algorithms: adjacent_find(), swap_range(), replace()

©Fraser Hutchinson & Cliff Green Bidirectional Iterators Support operator-- in addition to all the operations supported by forward iterators Used in algorithms: inplace_merge(), reverse() next_permutation()

©Fraser Hutchinson & Cliff Green Random Access Iterators Support all operations supported by forward and bidirectional iterators Provide access to any container element in constant time Adds remaining operators of pointer arithmetic addition and subtraction to pointer: (p+n), (p-n) subscripting: (p[n]) subtraction between iterators: (p1-p2) ordering (p1<p2) Used in algorithms: binary_search(), sort_heap() Supported by containers: vector, deque

©Fraser Hutchinson & Cliff Green Operations Allowed on Iterators ++p, p++all iterators *p as an rvalueinput iterators *p as an lvalueoutput iterators --p, p--reverse, bidirectional iterators p+n, p[n]random access iterators

©Fraser Hutchinson & Cliff Green Special Iterators Iterators used for insertion (“iterator adaptors”) –inserter –front_inserter –back_inserter Iterators used only to read elements (useful on const container declarations) –const_iterator Iterators used to traverse a list in reverse order –reverse_iterator –const_reverse_iterator

©Fraser Hutchinson & Cliff Green Vector Templatized ‘array’ of objects Automatically resizes if elements added (through push_back or insert methods) #include // appropriate “using” declarations vector myArray; for (int ii = 0; ii < 100; ++ii) { myArray.push_back(ii); }

©Fraser Hutchinson & Cliff Green Vector Details By default, vector does not perform range- checking. In the above case, the statement int val = myArray[100]; would give undefined results – if range checking desired, use at() method (throws exception if out of range)

©Fraser Hutchinson & Cliff Green List Lists are valuable if direct element access (through subscripting) is not needed typedef list MyStrings; // const iterator because we will not modify the list typedef list ::const_iterator Iter; MyStrings mystrings; // populate mystrings string const mymatch (“foo”); for (Iter i = mystrings.begin(); i != mystrings.end(); ++i) { if (*i == mymatch) //… do something }

©Fraser Hutchinson & Cliff Green List Operations Add an element to the end of the list: mystrings.push_back(my_string); Add an element to the front of the list: mystrings.push_front(my_string); Add the string before element referred to by iterator ‘i’: mystrings.insert (i, my_string); Erase the element referred to by iterator ‘i’: mystrings.erase (i);

©Fraser Hutchinson & Cliff Green Map When we want to access elements by a key value, we use a map. To access integer values by a string key: #include // appropriate using declarations map phonebook; void print_entry(string const & s) { cout << s << ‘ ‘ << phonebook[s] << \n” }

©Fraser Hutchinson & Cliff Green Map Details Subscript operator on map will create an element (default constructed), if needed –Using the insert method is frequently more appropriate Many operations use a std::pair, corresponding to the key and data values Third template parameter (typically defaulted) allows map sorting order to be changed

©Fraser Hutchinson & Cliff Green STL Algorithms STL algorithms are decoupled from the containers. STL algorithms may also be used with pointers and arrays. The category of iterator supported by a container determines whether the container can be used with a particular algorithm. –Mistakes are detected at compile-time.

©Fraser Hutchinson & Cliff Green Algorithms Sequence: a range in a container, specified by iterators start and end. –sort(iterator start, iterator end): sorts a sequence –unique_copy(iterator start, iterator end, iterator dest): makes a unique copy of a sequence –find(iterator start, iterator end, T val): searchs for val in the specified range, and returns an iterator to that element

©Fraser Hutchinson & Cliff Green Search Algorithms Search algorithms provide general strategies for finding if an element is in a container. Search algorithms –binary_search() –equal_range(), lower_bound(), upper_bound() –count(), count_if() –find(), find_end(), find_first_of(), find_if() –search()

©Fraser Hutchinson & Cliff Green Sorting and Ordering Algorithms merge() partial_sort(), partial_sort_copy() partition() random_shuffle() reverse(), reverse_copy() rotate(), rotate_copy() sort() A partition divides the container into two groups (those that satisfy a condition and those that don’t)

©Fraser Hutchinson & Cliff Green Deletion and Substitution Algorithms copy, copy_backwards() remove(), remove_copy(), remove_if(), remove_if_copy() replace(), replace_copy() replace_if(), replace_if_copy() swap(), swap_range(), unique()

©Fraser Hutchinson & Cliff Green More Algorithms Numeric algorithms –accumulate(), partial_sum() Generation and mutation algorithms –fill() –for_each() –generate() –transform()

©Fraser Hutchinson & Cliff Green Even More Algorithms Relational algorithms –equal() –includes() –max(), max_element() –min(), min_element() Set algorithms –set_union() –set_intersection() –set_difference()

©Fraser Hutchinson & Cliff Green Algorithm Constraints When not to use the generic algorithms –Cannot reorder associative containers associative containers internally maintain the order of their elements, so it is not permitted to use algorithms like sort() or partition() –Cannot use random access with a list specific list member instances of each algorithm are provided for algorithms like sort() or merge()

©Fraser Hutchinson & Cliff Green Functors Functors are objects that may be invoked with overloaded operator(). –Functors that return bool are called predicate functors. Many STL algorithms accept functors in their interfaces, for additional flexibilitity. Many functors are provided by STL –less, greater, equal_to –logical_and, logical_or –plus, minus, negate