Introduction to Templates and Standard Template Library 1.

Slides:



Advertisements
Similar presentations
Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
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.
Mutating Algorithms All the algorithms we have seen have not modified the containers Some algorithms do modify values They do not modify iterators, only.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Templates and Polymorphism Generic functions and classes.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
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)
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
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. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
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.
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Templates and Polymorphism Generic functions and classes
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
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
Containers Overview and Class Vector
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,
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
 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.
Array Size Macro approach 19 Macros Macros do not perform error checking. // macro approach #define macro_array_size(array) (sizeof(array)/sizeof(array[0]))
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Intro to the C++ Std Library.
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)
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
1 Iterators Good reference site:
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.
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.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
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.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
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.
Lecture 36 OOP The STL Standard Template Library
CS212: Object Oriented Analysis and Design
CNS 3370 Algorithms.
Standard Template Library (STL)
Collections Intro What is the STL? Templates, collections, & iterators
Chapter 22: Standard Template Library (STL)
CS212: Object Oriented Analysis and Design
Containers, Iterators, Algorithms, Thrust
Elements are always copied when they are put into a container
STL Библиотека стандартных шаблонов
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
Standard Template Library
Presentation transcript:

Introduction to Templates and Standard Template Library 1

Function Templates Function overloading allows the same function to act on different argument types: void swap2Items(int &n1, int &n2){ int temp = n2; n2 = n1; n1 = temp; } void swap2Items(card &n1,card &n2){ card temp = n2; n2 = n1; n1 = temp; } 2

Function Templates Function written as a template: template void swap2Items(T &n1, T &n2) { T temp = n2; n2 = n1; n1 = temp; } Compiler generates code for us when it comes across statements: swap2Items(j, k); //i and j are ints swap2Items(c1, c2); //c1 and c2 are cards 3

Function Templates This function will work with any defined type: Date d1, d2; swap2Items(d1,d2); With what condition? 4

Function Templates This function will work with any defined type: Date d1, d2; swap2Items(d1,d2); With what condition? Date class must have a valid assignment operator. operator= 5

Function Templates Function templates can even be overloaded template void swap2Items(T &x, S &y) { T temp = x; x = y; y = temp; } Which allows us to swap any object with any other object as long as we can assign between the two types. This now replaces the previous version with the special case S=T. 6

Class Templates Templates can also be used with classes. We can create generic classes that handle different types of data. A stack ADT is a FILO type. For the stack class: We may want stacks of integer, float, Date etc Without templates we have to create stacks for each of them, With templates we can create generic stacks 7

Class Templates A stack ADT is a FILO type. Here is the class declaration using templates: template class StackT{ public: StackT(int = 10) ; ~StackT() { delete [] stackPtr; } int push(const T&); int pop(T&) ; int isEmpty()const { return top == -1; } int isFull() const { return top == size - 1; } private: int size; int top; T* stackPtr; }; 8

Class Templates Template class constructor: template StackT ::StackT(int s){ size = s > 0 && s < 1000 ? s : 10; top = -1; //initialize stack stackPtr = new T[size]; } 9

Class Templates template int StackT ::push(const T& item){ if (!isFull()){ stackPtr[++top] = item; return 1; // push successful } return 0; // push unsuccessful } template int StackT ::pop(T& popValue) { if (!isEmpty()){ popValue = stackPtr[top--] ; return 1; // pop successful } return 0; // pop unsuccessful } 10

Class Templates Code for these template classes and functions are generated when they are used in code. int main() { StackT fs(5); float f = 1.1; while(fs.push(f)) { cout << f << ' '; f += 1.1; } 11

Templates vs Macros Macros present the possibility for side effects and avoid type checking. #define SQ(A) ((A)*(A)) template T square (T x){ return x*x; } 12

Templates vs Macros int main(){ int a = 7; cout << square(a++) << endl; cout << "and a is " << a << endl; cout << SQ(a++) << endl; cout << "and a is " << a << endl; } output: 49 and a is 8 64 and a is 10 13

Common Errors 1.Not using template when defining member function for class templates. 2.Not using the generic type for parameters/variables. 3.Not placing class, before every formal type parameter. Correct: template 4.If a template is invoked with a user defined class type and that template uses operators (==, +, <=) with objects of that class type, then those operator must be overloaded. 14

Standard Template Library A large collection of reusable components. The key components of the STL - containers are data structures created using templates. A container is an object that contain objects. Using STL can save considerable time and effort, and result in higher quality programs. 15

Standard Template Library STL is a set of general-purpose template classes, built using the template mechanism. The main ideas of STL are: Containers Iterators Algorithms 16

Standard Template Library Containers are objects that hold other objects. There are different types of containers: sequence containers: vector, deque, list associative containers for allowing efficient retrieval of values based on keys: map, sets 17

Vector Class Vectors are dynamic arrays: arrays that can grow as needed. template class vector{ //... }; When using the vector type the required header to be included is 18

Vector Class Declaring/Defining a vector: vector iv; vector cv(5); vector cv(5, 'x'); vector iv2(iv); 19

Vector Class Using a vector: // display original size of v cout<<"Size = "<<v.size()<<endl; // put values onto end of a vector // the vector will grow as needed for(int i = 0; i < 10; i++) { v.push_back(i); } // change contents of a vector for(int i = 0; i < v.size(); i++) { v[i] = v[i] + v[i]; } 20

Vector Class // access using subscripting for(int i = 0; i < 10; i++) { cout << v[i] << " "; } cout << endl; // access via iterator vector ::iterator p = v.begin(); while(p != v.end()) { cout << *p << " "; p++; }

Iterators An Iterator is just a convenient pseudo- pointer that is set up as a type to use associated with each container class. Various operators will have been set up to use with them eg =, ==, != and +=

Iterators int array[10]; for(int i = 0; i < 10; i++) { } Becomes vector v(10); vector ::iterator it; for(it = v.begin(); it != v.end(); it++) { }

Iterators Iterators are objects similar to pointers. They are design to give us the ability to cycle through the content of a container. There are five iterator types: input output forward bidirectional random access

Iterators Container classes and algorithms dictate the category of iterator available or needed. vector containers allow random-access iterators lists do not; sorting requires a random-access iterators find requires an input iterator.

Iterators Iterators can be adapted to provide backward traversal. Example that uses a reverse iterator to traverse a sequence. template void print(ForwIter first, ForwIter last, const char* title){ cout << title << endl; while ( first != last) cout << *first++ << '\t'; cout << endl; }

Iterators int main(){ int data[3] = { 9, 10, 11}; vector d(data, data + 3); vector ::reverse_iterator p = d.rbegin(); print(p, d.rend(), "Reverse"); //... }

STL Standard Components STL relies upon several other standard components for support: allocators: to manage memory allocation for a container predicates: special functions returning true/false results comparison functions, etc.

STL Algorithms Algorithms act on the contents of containers. They include capabilities for: initializing sorting searching and transforming the contents of containers. All algorithms are template functions. To access them: #include

STL Algorithms string words[5] = {"my", "hop", "mop", "hope”, "cope"}; string* where; where = find(words, words + 5, "hop"); cout << *++where << endl; //mop

STL Algorithms vector v; int i; for(i = 0; i < 10; ++i) v.push_back(i); cout << "Initial: "; for(i = 0; i < v.size(); ++i) cout << v[i] << " "; cout << endl; reverse(v.begin(), v.end());

Transform Reverse Algorithms #include using namespace std; double reciprocal( double d){ return 1.0 / d; } template void printVector( vector v ){ for(int j=0;j<v.size();j++){ cout << v[j] << " ”; } cout << endl; } int main(){ vector vals; for(int i=1;i<10;i++) vals.push_back((double)i); printVector( vals ); transform( vals.begin(), vals.end(), vals.begin(), reciprocal ); printVector( vals ); reverse( vals.begin(), vals.end() ); printVector( vals ); return 0; } Output Note use of function name identifier as an argument to transform transform takes arguments: start-iter, end-iter, result-iter, func Note use of template mechanism to write a generalised printVector function

Merge Algorithm #include using namespace std; template void printVector( vector v ){ for(int j=0;j<v.size();j++){ cout << v[j] << " "; } cout << endl; } int main(){ vector v1; for(int i=1;i<20;i+=2) v1.push_back( i ); vector v2; for(int i=0;i<20;i+=2) v2.push_back( i ); printVector( v1 ); printVector( v2 ); vector v3( v1.size() + v2.size() ); printVector( v3 ); merge( v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin() ); printVector( v3 ); return 0; } Output Note arguments: – start1, end1, start2, end2, result Returns end-iter of result (not used in this example)

STL Algorithms merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v3.begin()); printVector( v3 ); random_shuffle( v3.begin(), v3.end() ); printVector( v3 ); cout << "end - begin = " << v3.end() - v3.begin() << endl; cout << "Max is " << *max_element(v3.begin(), v3.end()) << endl; cout << "Min is " << *min_element(v3.begin(), v3.end()) << endl; sort(v3.begin(), v3.end()); printVector( v3 ); for_each(v3.begin(), v3.end(), sum); cout << "Sum was " << total << endl; vector v4; v4.push_back(11); v4.push_back(12); v4.push_back(13); cout << "subsequence included is " << includes(v3.begin(),v3.end(),v4.begin(),v4.end()) << endl; v4[1] = 10; cout << "subsequence included is " << includes(v3.begin(),v3.end(),v4.begin(),v4.end()) << endl; return 0; }

STL Algorithms adjacent_find binary_search copy copy_backward count count_if equal equal_range fill and fill_n find find_end find_first_of find_if for_each generate and generate_n includes inplace_merge iter_swap lexicographical_compare lower_bound make_heap max max_element merge min min_element mismatch next_permutation

STL Algorithms nth_element partial_sort partial_sort_copy partition pop_heap prev_permutation push_heap random_shuffle remove and remove_if… replace and replace_if… reverse and reverse_copy rotate and rotate_copy search search_n set_difference set_intersection set_symmetric_difference set_union sort sort_heap stable_partition stable_sort swap swap_ranges transform unique and unique_copy upper_bound

STL Summary Algorithms in the STL are just template functions There are some useful ones that may save you reinventing the wheel. Library functions have the great advantage - someone else has tested them!