C++ Standard Template Library

Similar documents
To use various types of iterators with the STL algorithms ( ). To use Boolean functions to specify criteria for STL algorithms ( 23.8).

Major Language Changes, pt. 1

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

Distributed Real-Time Control Systems. Lecture 16 C++ Libraries Templates

New Iterator Concepts

Boost.Compute. A C++ library for GPU computing. Kyle Lutz

How the Adapters and Binders Work

Parallelism and Concurrency in C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting

MODULE 35 --THE STL-- ALGORITHM PART III

Working Draft, Technical Specification for C++ Extensions for Parallelism, Revision 1

Parallelism in C++ J. Daniel Garcia. Universidad Carlos III de Madrid. November 23, 2018

C and C++ Courses. C Language

MODULE 37 --THE STL-- ALGORITHM PART V

I/O and STL Algorithms

Contents. 2 Introduction to C++ Programming,

SFU CMPT Topic: Function Objects

Programming Languages Technical Specification for C++ Extensions for Parallelism

Computing with functions

Deitel Series Page How To Program Series

Exceptions, Templates, and the STL

COMP6771 Advanced C++ Programming

Generic Programming with JGL 4

G Programming Languages Spring 2010 Lecture 11. Robert Soulé, New York University

Function Templates. Consider the following function:

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

The C++ Standard Template Library

CS11 Advanced C++ Fall Lecture 1

Data_Structures - Hackveda

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

C++ How To Program 10 th Edition. Table of Contents

Lecture-5. STL Containers & Iterators

CS 247: Software Engineering Principles. ADT Design

COEN244: Class & function templates

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)

Module 9. Templates & STL

Concurrency and Parallelism with C++17 and C++20. Rainer Grimm Training, Coaching and, Technology Consulting

Scientific programming (in C++)

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

CS197c: Programming in C++

Chapters and Appendices F J are PDF documents posted online at the book s Companion Website, which is accessible from.

use static size for this buffer

CS 247: Software Engineering Principles. C++ lambdas, bind, mem_fn. U Waterloo CS247 (Spring 2017)

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

/ binary_search example #include <iostream> // std::cout #include <algorithm> // std::binary_search, std::sort #include <vector> // std::vector

Recap: Can Specialize STL Algorithms. Recap: Can Specialize STL Algorithms. C++11 Facilities to Simplify Supporting Code

G52CPP C++ Programming Lecture 18

Foundations of Programming, Volume I, Linear structures

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

STL: C++ Standard Library

W3101: Programming Languages C++ Ramana Isukapalli

The STL <functional> Library

CS 211 Winter 2004 Sample Final Exam (Solutions)

CS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p.

The Standard Template Library. An introduction

Unit 4 Basic Collections

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

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

GJL: The Generic Java Library

Object-Oriented Programming for Scientific Computing

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

1. The term STL stands for?

C++ Standard Template Library

Constants, References

CS11 Introduction to C++ Spring Lecture 8

Chapter 5. The Standard Template Library.

Advanced C++ STL. Tony Wong

EL2310 Scientific Programming

This is a CLOSED-BOOK-CLOSED-NOTES exam consisting of five (5) questions. Write your answer in the answer booklet provided. 1. OO concepts (5 points)

Informatik I (D-ITET) Übungsstunde 9, Hossein Shafagh

CE221 Programming in C++ Part 1 Introduction

The STL <functional> Library

CS11 Advanced C++ Spring 2018 Lecture 2

Intermediate Programming, Spring 2017*

Containers in C++ and Java

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

primer 2005/1/19 18:36 page 843 #865

19.1 The Standard Template Library

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Module Operator Overloading and Type Conversion. Table of Contents

The Cut and Thrust of CUDA

CPSC 427a: Object-Oriented Programming

COPYRIGHTED MATERIAL. Index SYMBOLS. Index

Templates & the STL. CS 2308 :: Fall 2015 Molly O'Neil

List, Stack, and Queues

ECE 462 Exam 1. 6:30-7:30PM, September 22, 2010

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

PIC 10A Objects/Classes

Where do we go from here?

Functors. Cristian Cibils

Lecture on pointers, references, and arrays and vectors

CS 376b Computer Vision

C++ Modern and Lucid C++ for Professional Programmers

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

The C++ Standard Template Library (STL) Design Philosophy of the STL. Design Philosophy of the STL. STL Containers

Standard Template Library. Containers, Iterators, Algorithms. Sequence Containers. Containers

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

Strings and Stream I/O

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

MODULE 33 --THE STL-- ALGORITHM PART I

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

Transcription:

C++ Standard Template Library CS 247: Software Engineering Principles Generic Algorithms A collection of useful, typesafe, generic (i.e., type-parameterized) containers that - know (almost) nothing about their elements - focus mostly on membership (insert, erase) - know nothing about algorithms - can define their own iterators Reading: Eckel, Vol. 2 Ch. 6 Generic Algorithms A collection of useful, efficient, generic algorithms that - know nothing about the data structures they operate on - know (almost) nothing about the elements in the structures - operate on structures sequentially via iterators U Waterloo CS247 (Spring 2017) p.1/36 U Waterloo CS247 (Spring 2017) p.2/36 for_each find find_if find_end find_first_of adjacent_find count count_if mismatch equal search search_n copy copy_backward swap swap_ranges iter_swap transform replace replace_if replace_copy replace_copy_if STL Algorithms fill fill_n generate generate_n remove remove_if remove_copy remove_copy_if unique unique_copy reverse reverse_copy rotate rotate_copy random_shuffle partition stable_partition sort stable_sort partial_sort partial_sort_copy nth_element lower_bound upper_bound equal_range binary_search merge inplace_merge includes set_union set_intersection set_difference set_symmetric_difference push_heap pop_heap make_heap sort_heap min max min_element max_element lexicographical_compare next_permutation prev_permutation U Waterloo CS247 (Spring 2017) p.3/36 Overview Most STL algorithms "process" a sequence of data elements. - Traverse a sequence of elements bounded by two iterators. - Access elements through the iterators. - Operate on each element during traversal. template<class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val) points to first element in input range points past last element in input range U Waterloo CS247 (Spring 2017) p.4/36

C++ Templates (and STL) rely on "Duck Typing" C++ templates realize polymorphism through type parameters and what is called Duck Typing. If it walks like a duck, and talks like a duck, it must be a duck. An object of class C is type-compatible with a template parameter type T if it supplies all of the methods/method signatures used in the template. Example: template<class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val) Iterator Type Hierarchy The Iterator type hierarchy is based on duck typing the (sub)set of capabilities of the iterator. Any STL algorithm that requires an InputIterator as a parameter will also accept a fancier iterator in the type hierarchy. input iterator output iterator istream, ostream forward iterator unordered_set, unordered_multiset, unordered_map, unordered_multimap bidirectional iterator list, set, multiset, map, multimap random access iterator vector, deque U Waterloo CS247 (Spring 2017) p.5/36 U Waterloo CS247 (Spring 2017) p.6/36 Non-Modifying Algorithms A number of the algorithms read, but never write to, the elements in their input range. template<class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val) while ( first!= last ) if ( *first == val ) return first; ++first; return last; Algorithms over Two Sequences Algorithms that operate over two sequences of data specify the full range over the first sequence and only the start of the second sequence. template <class InputIterator1, class InputIterator2> bool equal ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 ) while ( first1!= last1 ) if (! ( *first1 == *first2 ) ) return false; ++first1; ++first2; return true; U Waterloo CS247 (Spring 2017) p.7/36 U Waterloo CS247 (Spring 2017) p.8/36

#include <iostream> #include <algorithm> #include <vector> using namespace std; // std::cout // std::equal // std::vector Modifying Algorithms Some algorithms overwrite element values in existing container. - We must take care to ensure that the destination sequence is large enough for the number of elements being written. int main () int myints[] = 11, 22, 33, 44, 55, 66; // myints: 11 22 33 44 55 66 vector<int>myvector (myints,myints+5); // myvector: 11 22 33 44 55 // using default comparison: operator== if ( equal (myvector.begin(), myvector.end(), myints) ) cout << "The contents of both sequences are equal.\n"; else cout << "The contents of both sequences differ.\n"; return 0; template<class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result) while ( first!= last ) *result = *first; ++result; ++first; return result; U Waterloo CS247 (Spring 2017) p.9/36 U Waterloo CS247 (Spring 2017) p.10/36 #include <iostream> #include <algorithm> #include <vector> using namespace std; // std::cout // std::equal // std::vector int main () int myints[] = 11, 22, 33, 44, 55, 66; Overwriting vs. Inserting The default behaviour is to write to a destination sequence, overwriting existing elements. Can impose insertion behaviour instead by providing an inserter iterator as the destination. vector<int>myvector (10); // myvector: 0 0 0 0 0 0 0 0 0 0 copy ( myints, myints+sizeof(myints), myvector.begin() ); cout << "myvector contains:" << endl; ostream_iterator<int> os (cout, "\n" ); copy ( myvector.begin(), myvector.end(), os ); cout << '\n'; return 0; U Waterloo CS247 (Spring 2017) p.11/36 U Waterloo CS247 (Spring 2017) p.12/36

"Removing" Elements template <class ForwardIterator, class T> ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val) Algorithms never directly change the size of containers need to use container operators to add/remove elements. Instead, algorithms rearrange elements sometimes placing undesirable elements at the end of the container and returning an iterator past the last valid element. no 42s 42 42 42 42 end vector<int>::iterator end = remove ( vec.begin(), vec.end(), 42); vec.erase ( end, vec.end() ); // to remove the 42s U Waterloo CS247 (Spring 2017) p.13/36 Algorithms that Apply Operations A number of algorithms apply operations to the elements in the input range: - e.g., transform(), count_if(), sort() Some STL algorithms accept a predicate: - applied to all elements in iteration - used to restrict set of data elements that are operated on bool gt20(int x) return 20 < x; bool gt10(int x) return 10 < x; int a[] = 20, 25, 10 ; int b[10]; remove_copy_if( a, a+3, b, gt20 ); // b[] == 25; cout << count_if( a, a+3, gt10 ); // Prints 2 U Waterloo CS247 (Spring 2017) p.14/36 Function Objects If we need a function that that refers to data other than the iterated elements, we need to define a function object (aka functor). class that overloads operator ( ), the function call operator. operator ( ) allows an object to be used with function call syntax. class gt_n int value_; gt_n(int val) : value_(val) bool operator()(int n) return n > value_; ; constructor int main() gt_n gt4(4); function calls cout << gt4(3) << endl; // Prints 0 (for false) cout << gt4(5) << endl; // Prints 1 (for true) Eckel, Allison, Thinking in C++, Vol. 2, Prentice Hall, 2004 U Waterloo CS247 (Spring 2017) p.15/36 Function Objects // We supply this function object class gt_n int value; gt_n(int val) : value(val) bool operator()(int n) return n > value; ; int main() int a[] = 5, 25, 10 ; gt_n gt15(15); cout << count_if( a, a+3, gt15 ); // Prints 1 cout << count_if( a, a+3, gt_n(0) ); // Prints 3 Eckel, Allison, Thinking in C++, Vol. 2, Prentice Hall, 2004 U Waterloo CS247 (Spring 2017) p.16/36

Another Example class inc inc(int amt) : increment_(amt) int operator()(int x) return x + increment_; private: int increment_; ; input range Transform over Two Sequences int add (int a, int b) return a + b; int main () int A[]=11,22,33,44,55,66,77; vector<int> V ( 7, 10 ); // seven elements of value 10 transform ( A, A+sizeof(A), V.begin(), V.begin(), add ); transform( V.begin(), V.end(), D.begin(), inc( 100 ) ); points to first element in input range points past last element in input range destination of results of transformation unary operation points to first element in first range points past last element in first range points to first element in second range destination of results of transformation binary operation U Waterloo CS247 (Spring 2017) p.17/36 U Waterloo CS247 (Spring 2017) p.18/36 Classification of Function Objects Generator: A type of function object that: - takes no arguments - returns a value of an arbitrary type Unary Function: A type of function object that : - takes a single argument of any type - returns a value that may be of a different type (which may be void) Binary Function: A type of function object that - takes two arguments of any two (possibly distinct) types - returns a value of any type (including void) Unary Predicate: A Unary Function that returns a bool. Binary Predicate: A Binary Function that returns a bool. Predefined Function Objects Header <functional> defines a number of useful generic function objects - plus<t>, minus<t>, times<t>, divides<t>, modulus<t>, negate<t> - greater<t>, less<t>, greater_equal<t>, less_equal<t>, equal_to<t>, not_equal_to<t> - logical_and<t>, logical_or<t>, logical_not<t> Can be used to customize many STL algorithms. For example, we can use function objects to override the default operator used by an algorithm. For example, sort by default uses operator<. To instead sort in descending order, we could provide the function object greater<t> to sort. sort(myvector.begin(), myvector.end(), greater<int>()); U Waterloo CS247 (Spring 2017) p.19/36 U Waterloo CS247 (Spring 2017) p.20/36

Predefined Function Object Adaptors <functional> also defines a number of useful generic adaptors to modify the interface of a function object. bind1st - convert a binary function object to a unary function object (by fixing the value of the first operand) bind2nd - convert a binary function object to a unary function object (by fixing the value of the second operand) mem_fun - convert a member function into a function object (when member function is called on pointers to objects) mem_fun_ref - convert a member function into a function object (when member function is called on objects) not1 - a function adaptor that reverses the truth value of a unary predicate object not2 - a function adaptor that reverses the truth value of a binary predicate object ptr_fun - convert a function pointer to a function object so that a generic adaptor can be applied otherwise, can simply use function pointer U Waterloo CS247 (Spring 2017) p.21/36 Function Object Adaptors Example: Convert a binary function object to a unary function object bind2nd( greater<int>(), 15 ); // x > 15 bind1st( minus<int>(), 100); // 100 - x Example: Convert a member function into a function object vector<string> strings; vector<shape*> shapes; transform( strings.begin(), strings.end(), dest, mem_fun_ref( &string::length ) ); transform( shapes.begin(), shapes.end(), dest2, mem_fun( &Shape::size ) ); U Waterloo CS247 (Spring 2017) p.22/36 Adaptable Function Objects To be adaptable, a function object class must provide nested type definitions for its arguments and return type: typedef T1 argument_type; unary typedef T2 result_type; typedef T3 first_argument_type; typedef T4 second_argument_type; function object binary function object Function Object Adaptors are Function Objects! template <class Operation> class binder2nd : public unary_function <typename Operation::first_argument_type, typename Operation::result_type> protected: Operation op; typename Operation::second_argument_type value; binder2nd ( const Operation& x, const typename Operation::second_argument_type& y) : op (x), value(y) typename Operation::result_type operator() (const typename Operation::first_argument_type& x) const return op(x,value); ; bind2nd() is a template function that outputs a binder2nd<op> object - protected data member binfunc (binary operation) - protected data member value (value of second argument) - public constructor (Op& binfunc, secondargtype value) - operator() (firstargtype& x) returns op(x, value); U Waterloo CS247 (Spring 2017) p.23/36 U Waterloo CS247 (Spring 2017) p.24/36

Adaptable Function Objects Since these names are expected of all standard function objects as well as of any function objects you create to use with function object adaptors, the <functional> header provides two templates that define these types for you: unary_function and binary_function. You simply derive from these classes while filling in the argument types as template parameters. Suppose, for example, that we want to make the function object gt_n, defined earlier in this chapter, adaptable. All we need to do is the following: Can create our own adaptable function objects by deriving from unary_function or binary_function. class gt_n : public unary_function<int, bool> int value; gt_n(int val) : value(val) bool operator()(int n) return n > value; ; STL Example: Course Schedule Adapted from Doug Schmidt Goals: Read in list of course names and scheduled times. - Day of week is read in as character: M,T,W,R,F,S,U. - Time is read as integer in 24-hour HHMM format. Sort list according to day and then by time of day. Detect any overlaps between courses and print them out. Print out ordered schedule for the week. Use STL to perform as much of the above as possible. U Waterloo CS247 (Spring 2017) p.25/36 U Waterloo CS247 (Spring 2017) p.26/36 STL Example: Course Schedule (cont.) > cat infile >./sched infile #include <iostream> #include <string> Course.h CS442 M 1030 1200 CS442 W 1030 1200 CS444 T 1600 1730 CS444 R 1600 1730 CS445 M 1130 1300 CS445 F 1130 1300 CS457 M 1330 1430 CS457 W 1330 1430 CS457 F 1330 1430 CONFLICT: CS442 M 1030 1200 CS445 M 1130 1300 CS442 M 1030 1200 CS445 M 1130 1300 CS457 M 1330 1430 CS444 T 1600 1730 CS442 W 1030 1200 CS457 W 1330 1430 CS444 R 1600 1730 CS445 F 1130 1300 CS457 F 1330 1430 U Waterloo CS247 (Spring 2017) p.27/36 enum class DayOfWeek M, T, W, R, F, S, U; class Course friend std::ostream& operator<< (std::ostream&, const Course&); Course (std::string title, char day, int starttime, int endtime); bool overlaps (const Course&) const; // detects conflicts bool before (const Course&) const; // used in sorting private: std::string title_; DayOfWeek day_; int starttime_; int endtime_; ; std::ostream& operator<< (std::ostream&, const Course&); U Waterloo CS247 (Spring 2017) p.28/36

Course.cpp Course.cpp #include <cassert> #include <iostream> #include "Course.h" using namespace std; const std::string DayToString[] = "M ", "T ", "W ", "R ", "F ", "S ", "U "; DayOfWeek dayofweek (char c) switch (c) case 'M': return DayOfWeek::M; case 'T': return DayOfWeek::T; case 'W': return DayOfWeek::W; case 'R': return DayOfWeek::R; case 'F': return DayOfWeek::F; case 'S': return DayOfWeek::S; case 'U': return DayOfWeek::U; default: assert ( 0 && "not a week day" ); U Waterloo CS247 (Spring 2017) p.29/36 Course::Course (string title, char day, int starttime, int endtime) : title_title, day_dayofweek(day), starttime_starttime, endtime_endtime bool Course::before (const Course& c) const if ( day_ < c.day_ ) return true; if ( day_ == c.day_ ) if ( starttime_ < c.starttime_ ) return true; if ( starttime_ == c.starttime_ ) if ( endtime_ < c.endtime_ ) return true; return false; U Waterloo CS247 (Spring 2017) p.30/36 Course.cpp bool Course::overlaps ( const Course& c) const if ( day_ == c.day_ && (( starttime_ <= c.starttime_ && c.starttime_ <= endtime_ ) ( c.starttime_ <= starttime_ && starttime_ <= c.endtime_ )) ) return true; #include <iostream> #include <fstream> #include <string> #include <vector> #include <iterator> #include <algorithm> #include "Course.h" using namespace std; main.cpp return false; ostream& operator<< (ostream &os, const Course &c) return (os << c.title_ << " " << DayToString[static_cast<int>(c.day_)] << " " << c.starttime_ << " " << c.endtime_); // Forward declare helper routines. int inputcourses (int argc, char *argv[], vector<course> &schedule); void printconflicts (vector<course> &schedule); void printschedule (vector<course> &schedule); int main (int argc, char *argv[]) vector<course> schedule; if ( inputcourses( argc, argv, schedule ) < 0 ) return -1; sort ( schedule.begin(), schedule.end(), mem_fun_ref( &Course::before ) ); printconflicts ( schedule ); printschedule ( schedule ); U Waterloo CS247 (Spring 2017) p.31/36 return 0; U Waterloo CS247 (Spring 2017) p.32/36

main.cpp int inputcourses (int argc, char *argv[], vector<course> &schedule) if ( argc < 2 ) return -1; ifstream ifile (argv[1]); string title; char day; int starttime; int endtime; while (ifile >> title >> day >> starttime >> endtime) Course c (title, day, starttime, endtime); schedule.push_back(c); return ifile.eof()? 0 : -1; U Waterloo CS247 (Spring 2017) p.33/36 main.cpp void printconflicts (vector<course> &schedule) vector<course>::iterator iter = schedule.begin(); vector<course>::iterator end = schedule.end(); while ( ( iter = adjacent_find( iter, end, mem_fun_ref(&course::overlaps)) )!= end ) cout << "CONFLICT:" << endl << " " << *iter << endl << " " << *(iter+1) << endl << endl; iter++; void printschedule (vector<course> &schedule) ostream_iterator<course> iter (cout, "\n"); copy (schedule.begin(), schedule.end(), iter); U Waterloo CS247 (Spring 2017) p.34/36 Summary of STL Algorithms Generic algorithms process sequences of data of any type in a type-safe manner. process: generate, search, transform, filter, stream, compare,... sequences of data: algorithms iterate over elements in a sequence of any type: algorithms are function templates that parameterize the type of iterator (the type of data is mostly irrelevant) type-safe: compiler detects and reports type errors Concluding Remarks The goal of the STL is to provide a set of data structures and algorithms that are: generic parameterized by type strongly typed e.g., vector<figure *> flexible large APIs, many possible modes of use extensible inherit/extend for your own needs OR create a specialized, restricted API via adapters efficient static method dispatch, specialized algorithms (relatively) easy to use U Waterloo CS247 (Spring 2017) p.35/36 U Waterloo CS247 (Spring 2017) p.36/36