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

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

Exceptions, Templates, and the STL

TEMPLATES AND ITERATORS

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

Modularity. Modular program development. Language support for modularity. Step-wise refinement Interface, specification, and implementation

CS11 Advanced C++ Fall Lecture 1

The Standard Template Library. An introduction

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

Structuur van Computerprogramma s 2

Chapter 5. The Standard Template Library.

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Container Class and Integrators, Proxy Class EC6301-OOPS AND DATA STRUCTURES

1. The term STL stands for?

7 TEMPLATES AND STL. 7.1 Function Templates

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

Standard Template Library

Introduction to Computer Science Midterm 3 Fall, Points

CS11 Introduction to C++ Spring Lecture 8

Dynamic Data Structures

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

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer.

STL: C++ Standard Library

CS197c: Programming in C++

C++ is Fun Part 11 at Turbine/Warner Bros.! Russell Hanson

Linked Lists. Gaddis Ch. 17. CS 2308 :: Spring 2016 Molly O'Neil

! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible.

COEN244: Class & function templates

C++ Standard Template Library

C and C++ Courses. C Language

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class

Programming II (CS300)

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

2

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University

Topics. Modularity and Object-Oriented Programming. Dijkstra s Example (1969) Stepwise Refinement. Modular program development

Cpt S 122 Data Structures. Templates

Lecture-5. STL Containers & Iterators

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

Question Paper Code : 97044

The following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs.

1 Short Answer (7 Points Each)

CS201 - Introduction to Programming Glossary By

Chapter 17: Linked Lists

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Assignment 1: grid. Due November 20, 11:59 PM Introduction

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

Containers and the Standard Template Library (STL)

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

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

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

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Vectors. CIS 15 : Spring 2007

Homework #3 CS2255 Fall 2012

by Pearson Education, Inc. All Rights Reserved. 2

Computational Physics

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

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

Class and Function Templates

DELHI PUBLIC SCHOOL TAPI

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

cs Java: lecture #6

Object-Oriented Programming

Lecture 4a Using The Standard Template Library. Jack Applin, Guest Lecturer

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

EECE.2160: ECE Application Programming

Short Notes of CS201

CSCI-1200 Data Structures Fall 2018 Lecture 22 Hash Tables, part 2 & Priority Queues, part 1

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Financial computing with C++

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

Arrays and Linked Lists

Templates and STL Vectors

Life cycle of an object construction: creating a new object. Strings: constructors & assignment another type that C and C++ don't provide

Exercise 6.2 A generic container class

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

An Introduction to C++

5 Phases of Software Life Cycle

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Programming II (CS300)

Programming in C++: Assignment Week 1

arrays review arrays and memory arrays: character array example cis15 advanced programming techniques, using c++ summer 2008 lecture # V.

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

CS

List, Stack, and Queues

4.1 Ordered Lists Revisited

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

CS201 Some Important Definitions

CS 162, Lecture 25: Exam II Review. 30 May 2018

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition?

CS 32. Lecture 5: Templates

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

C# Adds Useful Features

CPSC 427a: Object-Oriented Programming

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

Transcription:

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

Function Templates Let's say we have a program that repeatedly needs to find the maximum value in an array In one place in our code, we need the max of an array of ints but in another place, it's an array of doubles and in a third place, it's an array of Time objects! We can declare three findmaximum() functions and duplicate a lot of code, or We can use a function template: a pattern for a function that can work with multiple data types Data types in the function are specified as parameters Compiler generates code for the function to match the specific data type(s) used where the function is called 2

Function Template Example template <class T> T findmaximum(t arr[], int size) { T max = arr[0]; // don't call this fn with size <= 0! for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; int main() { int intarr[10]; double doublearr[7]; Time timearr[5]; int imax = findmaximum(intarr, 10); double dmax = findmaximum(doublearr, 7); Time tmax = findmaximum(timearr, 5); 3

Function Template Example This function call int main() { int intarr[10]; int imax = findmaximum(intarr, 10); Causes the compiler to generate this function: int findmaximum(int arr[], int size) { int max = arr[0]; for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; 4

Function Template Example And this function call int main() { double doublearr[7]; double dmax = findmaximum(doublearr, 7); Causes the compiler to generate this function: double findmaximum(double arr[], int size) { double max = arr[0]; for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; 5

Function Template Example And this function call int main() { Time timearr[5]; Time tmax = findmaximum(timearr, 5); Causes the compiler to generate this function: Time findmaximum(time arr[], int size) { Time max = arr[0]; for(int i = 1; i < size; i++) { if(max < arr[i]) max = arr[i]; return max; Note that this only works because we have overloaded the < operator for the Time class! 6

More About Function Templates Function template is a pattern only; no actual code is generated until the function is called You can define a template to use multiple data types: template<class T1, class T2> Just like functions can be overloaded, function templates can be overloaded Must have unique parameter lists template <class T> T sumall(t num) template<class T1, class T2> T1 sumall(t1 num1, T2 num2) When passing a class object to a function template, be sure that all operators in the template are defined/ overloaded in the class definition! 7

Class Templates Classes can also be represented by templates A class template is a pattern for a class definition that parameterizes the type of class member variables Also called a templated class or a parameterized class An object of a templated class is a specialization When a class object is created, type information is supplied to define the type of the class member variables Object instantiation requires supplying the type name at object definition 8

Class Template Example For example, we can design a generic Linked List class as a templated class Rather than writing separate IntList, DoubleList, TimeList, SongList, etc. classes template <class T> class LinkedList { private: class Node { public: T data; Node *next; ; Node *head; public: LinkedList(); ~LinkedList(); void insert(t); void remove(t); void display(); 9

Using Class Templates Programmer passes the type information to the class template when an object of the class is instantiated: LinkedList<int> intlist; LinkedList<double> doublelist; LinkedList<Song> songlist; Once defined, the object can be treated as an ordinary object Song s1("hey Jude", "The Beatles", 2.5); songlist.insert(s1); 10

The Standard Template Library (STL) The Standard Template Library (STL) is a library containing templates for frequently used data structures and algorithms Not a part of C++ and unsupported by older compilers But standard in newer versions and commonly-used Two important types of data structures in the STL: Containers: classes that store data and impose some organization on it Iterators: mechanism for accessing elements in a container (somewhat like pointers) 11

STL Containers Sequence containers: organize and access data sequentially. E.g.: Vector An array that can dynamically change in size (by internal re-allocation). Good for insertion/removal at back; random access to elements Dequeue (pronounced "deck") A double-ended queue, usually (but not mandatorily) implemented as multiple dynamic arrays linked together internally. Good for insertion/ removal at front or back; random access to elements List A doubly-linked list. Good for insertion/removal at front or back; must iterate list for random access Associative containers: use keys to allow data elements to be quickly accessed (you'll learn more about these in Data Structures). E.g.: Set / Multiset Map / Multimap 12

STL Iterators A generalization of pointers, used to access elements of a container Five overlapping types: Forward (can be incremented, i.e. ++) Bidirectional (can also be decremented, i.e. ++ and --) Random-access (can access elements at arbitrary positions relative to the element they point to) Input (can be used in input operations with cin/istream objects) Output (can be used in output operations with cout/ostream objects) 13

STL Algorithms STL also contains algorithms implemented as function templates to perform operations on the STL containers Must #include <algorithm> Includes (among others): binary_search sort count find find_if for_each min_element max_element random_shuffle 14