Download presentation
Presentation is loading. Please wait.
Published byElvin George Modified over 9 years ago
1
Templates&STL
2
Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them. Benefit of OOP is Code Reusability Templates are Used for this Purpose Two Types of Templates Function Templates Class Templates Same Operation on Different Types of Data Rough Sketch
3
Function Templates Functions For SWAPPING TWO VALUES 1. Using Function Overloading 2. Using Function Templates Some Functions we may need often which work on Different Data Types ANY METHOD ? YES OVERLOADING Disadvantage : Write One type function for One type of Data passed to it Using Function Templates It can be overcome Example: Next Slide Great !!!
4
void swap(char &x, char &y) { char t; t=x; x=y; y=t; } void swap(int &x, int &y) { int t; t=x; x=y; y=t; } void swap(float &x, float &y) { float t; t=x; x=y; y=t; } void swap(char &x, char &y) { char t; t=x; x=y; y=t; } void swap(int &x, int &y) { int t; t=x; x=y; y=t; } void swap(float &x, float &y) { float t; t=x; x=y; y=t; } void main() { char ch1, ch2; cin>>ch1>>ch2; swap(ch1, ch2); // compiler invokes swap(char &x, char &y); cout<< ch1<< ch2<<endl; int a, b; cin>>a>>b; swap(a, b); // compiler invokes swap(int &x, int &y); cout<<a<< b<<endl; float c, d; cin>>c>>d; swap(c, d); // compiler invokes swap(float &x, float cout<<c<< d<<endl; } void main() { char ch1, ch2; cin>>ch1>>ch2; swap(ch1, ch2); // compiler invokes swap(char &x, char &y); cout<< ch1<< ch2<<endl; int a, b; cin>>a>>b; swap(a, b); // compiler invokes swap(int &x, int &y); cout<<a<< b<<endl; float c, d; cin>>c>>d; swap(c, d); // compiler invokes swap(float &x, float cout<<c<< d<<endl; } Example Using Function Overloading
5
Such functions can be declared as a single function template without redefining them for each and every data type. The C++ template feature enables substitution of a single piece of code for all these overloaded functions with a single template function as follows: template void swap(T &x, T &y) { T t; t = x; x = y; y =t; } Such functions can be declared as a single function template without redefining them for each and every data type. The C++ template feature enables substitution of a single piece of code for all these overloaded functions with a single template function as follows: template void swap(T &x, T &y) { T t; t = x; x = y; y =t; } When swap operation is requested on operands of any data type, the compiler creates a function internally without the user intervention and invokes the same. Function Templates
6
keyword template data types at least one argument must be template type template ReturnType FunctionName (arguments) { ……// body of the template function …… } Syntax: Function Templates template void swap(T &x, T &y) { T t; t = x; x = y; y =t; }
7
Example: Functions For SWAPPING TWO VALUES Using Function Templates void main() { char ch1, ch2; cin>>ch1>>ch2; swap(ch1, ch2); cout<<ch1<< “ “<<ch2<<endl; int a, b; cin>>a>>b; swap(a, b); cout<<a<< “ “<<b<<endl; float c, d; cin>>c>>d; swap(c, d); cout<<c<< “ “<<d<<endl; } # include template void swap(T &x, T &y) { T t; t = x; x = y; y =t; } compiler calls swap(int &x, int &y);compiler calls swap(float &x, float &y);compiler calls swap(char &x, char &y); Cool !!!
8
void main() { // max with character data types char ch, ch1, ch2; cout : “; cin>>ch1>>ch2; ch=Max(ch1, ch2); cout<<”Max(ch1, ch2):” <<ch<<endl; // max with integer data types int a, b, c; cout : “; cin>>a>>b; c=Max(a, b); cout<<”Max(a, b):” <<c<<endl; // max with float data types int f1, f2, f3; cout : “; cin>>f1>>f2; f3=Max(f1, f2); cout<<”Max(f1, f2): “<<f3<<endl; } #include template T Max(T a, T b) { if (a>b) return a; else return b; } More Example: Using Function Templates Kool !!!
9
Class Templates A class template specifies how individual classes can be constructed similar to normal class specification. Class can also operate on different data types class CharStack { char array[25]; int top; public: CharStack(); void Push( const char &element); char Pop(void); int GetSize(void) const; }; class IntStack { int array[25]; int top; public: IntStack(); void Push( const int &element); int Pop(void); int GetSize(void) const; }; We need to Write two different Class - One for Integer / One for Char template class DataStack { T array[25];// declare a stack of 25 elements of data type T int top; public: DataStack(); void Push(const T &element); T Pop(void); int GetSize(void) const; }; template class DataStack { T array[25];// declare a stack of 25 elements of data type T int top; public: DataStack(); void Push(const T &element); T Pop(void); int GetSize(void) const; }; Only One Class Type for all types of arrays
10
Standard Template Library
11
STL is a part of Standard C++ Library OPERATIONS STL provide C++ with DATA STRUCTURES and OPERATIONS on those data types e.g., : STACKS - Operations such as PUSH and POP Components of STLContainersalgorithmsiterators Collection of Objects EG: vectors, stacks,queues In other words they are data structures Is a function for processing Container’s Content EG: Sort,Merge Containers Is a Mechanism for accessing objects in a container one at a time
12
Computer Programming II 12 Reasons for Using STL STL Containers unlike C++ arrays can grow and shrink in size automatically Program for Average of Integers : 1. Define a Large array 2. Fill them 3. Constantly Check for Overflow Disadvantage : Tedious and Error Prone The Same operation can be done using DMA Disadvantage : Still Tedious and Error Prone Such problems are eliminated with STL Containers - because they grow and shrink automatically - makes programming easy,efficient,robust
13
Example-1: Double each element for (I = 0 ; I<n ; I++) { array[I] * = 2; } We have to keep track of the Lower and upper bounds of the array #include vector v; // fill up v with values for_each(v.begin( ),v.end( ),sq); Automatically the lower and upper bounds will be kept track off
14
More Example on:STL vector container #include int main( ) { int I; vector nums; nums.insert(nums.begin( ), -99); nums.insert(nums.begin( ), 14); nums.insert(nums.end( ), 50); for (I=0; I <nums.size( ); I++) cout<<nums[I]<<endl; nums.erase(nums.begin( )); for (I=0; I <nums.size( ); I++) cout<<nums[I]<<endl; return 0; } -99 50 14 -99 50 14
15
Computer Programming II 15 Container Basics STL contains 7 containers - divided into two groups. List - linked list of elements vector- arrays which grows & shrinks dequeue - Arrays with insertion/deletions set - Collection of nonduplicate keys multiset- A set with duplicates map - Collection on non duplicates with access key multimap- A map with duplicates Sequential Associative
16
Computer Programming II 16 Container Adaptor A container adaptor adapts a container to behave in a particular way Three adaptors : stack,queue,priority queue Stack adaptor - creates a LIFO list Queue adaptor- creates a FIFO list
17
Computer Programming II 17 Algorithms STL has a rich assortment of algorithms for processing containers Categories :sorting, searching, copying and so on STL classes are implemented as template classes STL algorithms are implemented as template functions Template void reverse(bidirectionalIterator I1, BidirectionalIterator I2)); Two arguments are iterators,which can traverse a container from either end
18
Computer Programming II 18 STL Algorithms sort() algorithm STL Algorithms sort() algorithm #include int main( ) { vector v; vector v1; sort(v.begin( ),v.end( )); sort(v1.begin( ),v1.end( )); //… }
19
Abstract Data Type (ADT) - An Abstract Data Type is a set objects together with a set of operations. Data Structure - A construct within a programming language that stored a collection of data add sortAccordingToIDs display changeMark Data Structure interface of ADT Program ADT ADT-Abstract Data Type
20
What is ADT List A collection of elements of the same type Operations : Create the list; initialized to an empty state Determine whether the list is empty Determine whether the list is full Find the size of the list Destroy, or clear, the list Determine whether an item is the same as a given list element Insert an item in the list at the specified location Remove an item from the list at the specified location Replace an item at the specified location with another item Retrieve an item from the list at the specified location Search the list for a given item
21
Array-based List : STL's vector class STL = Standard Template Library - three basic components : - containers (Sequence, Associative, Container adapters) - iterators - algorithms STL's Sequence Containers : - three types : vector, deque, list STL's vector class : - Sequential container which can be accessed in a random access manner. - implemented as an array which can resize dynamically when required.
22
Computer Programming II 22 Major operations of STL's vector class : push_backadd an item to the end of the container pop_backremove an item from the end of the container atreturn the item given a position operator[]return the item given a position frontreturn the first item in the container backreturn the last item in the container sizereturn the size of the container capacityreturn the capacity of the container emptycheck if the container is empty resizeresize the container clearclear all the items in the container
23
#include using namespace std; int main() { vector v; v.push_back(4); v.push_back(2); v.push_back(1); v.push_back(6); v.push_back(8); v.push_back(3); for (int i=0;i<6;i++) cout << v[i] << " "; } 4 2 1 6 8 3 output: must include this push the item to the end of the array The vector class is parameterized class (generic class) using template, you need to specify the type of data to be stored. The items are accessed just as if they are array elements More Example of vector class :
24
Computer Programming II 24 #include using namespace std; int main() { vector v; int n; do { cout "; cin >> n; if (n!=-1) v.push_back(n); } while (n!=-1); for (int i=0;i<v.size();i++) cout << v[i] << " "; } => 1 => 5 => 3 => 2 => -1 1 5 3 2 output: return the size Demonstrate that you do not need to worry about memory allocating for it :
25
Computer Programming II 25 int main() { vector v; v.push_back(5); v.push_back(1); cout << "size = " << v.size() << endl; v.push_back(3); v.push_back(7); v.push_back(4); cout << "size = " << v.size() << endl; v.pop_back(); v.pop_back(); cout << "size = " << v.size() << endl; for (int i=0;i<v.size();i++) cout << v[i] << " "; cout << endl; } size = 2 size = 5 size = 3 5 1 3 output: Demonstrate that the vector class will automatically increase its internal storage capacity when required : remove item from end
26
Computer Programming II 26 int main() { vector v; string name; do { cout "; cin >> name; if (name!="quit") v.push_back(name); } while (name!="quit"); for (int i=0;i<v.size();i++) cout << v[i] << endl; } => shohel => dominic => angeline => bllaw => norhana => azzyati => quit shohel dominic angeline bllaw norhana azzyati output: Demonstrate that the vector class can be used with any data type : There are many more operation you can perform using the vector class, you need to refer to the STL documentation for more details.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.