Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending...

26
Templates Templates & & STL STL

Transcript of Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending...

Page 1: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

TemplatesTemplates

& &

STLSTL

Page 2: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 2

IntroductionIntroduction

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 TemplatesSame Operation on Different Types of Data

RoughSketch

Page 3: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Function TemplatesFunction Templates

Functions For SWAPPING TWO VALUES 1. Using Function Overloading2. 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 !!!Great !!!

Page 4: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

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

Page 5: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

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 <class T>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 <class T>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 TemplatesFunction Templates

Page 6: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

keyword template data types

at least one argumentmust be template type

template <class T, … >ReturnType FunctionName (arguments){

…… // body of the template function……

}

Syntax: Syntax: Function TemplatesFunction Templates

template <class T>void swap(T &x, T &y){

T t; t = x;x = y;y =t;

}

Page 7: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

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 <iostream.h>

template <class T>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 !!!

Page 8: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

void main(){

// max with character data typeschar ch, ch1, ch2;cout<<”Enter two characters <ch1, ch2>: “;cin>>ch1>>ch2;ch=Max(ch1, ch2);cout<<”Max(ch1, ch2):” <<ch<<endl;

// max with integer data typesint a, b, c;cout<<”Enter two integers <a, b>: “;cin>>a>>b;c=Max(a, b);cout<<”Max(a, b):” <<c<<endl;

// max with float data typesint f1, f2, f3;cout<<”Enter two integers <f1, f2>: “;cin>>f1>>f2;f3=Max(f1, f2);cout<<”Max(f1, f2): “<<f3<<endl;

}

#include <iostream.h>

template <class T>T Max(T a, T b){

if (a>b)return a;else return b;

}

More Example: Using Function Templates

Kool !!!

Page 9: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Class TemplatesClass Templates

A class template specifies how individual classes can be A class template specifies how individual classes can be constructed similar to normal class specification. constructed similar to normal class specification.

Class can also operate on different data typesClass 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 CharWe need to Write two different Class - One for Integer / One for Char

template <class T>class DataStack{

T array[25]; // declare a stack of 25 elements of data type Tint top;public:

DataStack();void Push(const T &element);T Pop(void);int GetSize(void) const;

};

template <class T>class DataStack{

T array[25]; // declare a stack of 25 elements of data type Tint top;public:

DataStack();void Push(const T &element);T Pop(void);int GetSize(void) const;

};

Only One Class Type for all types of arraysOnly One Class Type for all types of arrays

Page 10: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Standard Standard Template Template LibraryLibrary

Page 11: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Standard Template LibraryStandard Template Library

STL is a part of Standard C++ Library

STL provide C++ with DATA STRUCTURES and OPERATIONSOPERATIONS on those data types

e.g., : STACKS - Operations such as PUSH and POP

Components of STL Containers algorithms iterators

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

Page 12: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 12

Reasons for Using STLReasons 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

Page 13: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Example-1: Double each elementExample-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>

vector<int > v;

// fill up v with values

for_each(v.begin( ),v.end( ),sq);

Automatically the lower and Automatically the lower and upper bounds will be kept upper bounds will be kept

track offtrack off

Page 14: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

More Example on:STL More Example on:STL vectorvector container container#include <vector>int main( ){ int I;

vector<int > 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( ));nums.erase(nums.begin( ));

for (I=0; I <nums.size( ); I++)cout<<nums[I]<<endl;

return 0;}

-99-99

5050

1414

-99-99

5050

1414

Page 15: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 15

Container BasicsContainer BasicsSTL 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

SequentialSequential

AssociativAssociativee

Page 16: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 16

Container AdaptorContainer 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

Page 17: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 17

AlgorithmsAlgorithms 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 <class bidirectionaIterator>

void reverse(bidirectionalIterator I1, BidirectionalIterator I2));

Two arguments are iterators,which can traverse a container from either

end

Page 18: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 18

STL Algorithms

sort() algorithm

STL Algorithms

sort() algorithm

#include <vector>

#include <algorithm>

int main( )

{

vector<int > v;

vector<float > v1;

sort(v.begin( ),v.end( ));

sort(v1.begin( ),v1.end( ));

//…

}

Page 19: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

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

changeMarkData

Structure

interface of ADT

Program

ADT

ADT-Abstract Data TypeADT-Abstract Data Type

Page 20: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

What is ADT ListWhat 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

Page 21: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Array-based List : STL's Array-based List : STL's vectorvector class 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.

Page 22: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 22

Major operations of STL's vector class :

• push_back add an item to the end of the container

• pop_back remove an item from the end of the container

• at return the item given a position

• operator[] return the item given a position

• front return the first item in the container

• back return the last item in the container

• size return the size of the container

• capacity return the capacity of the container

• empty check if the container is empty

• resize resize the container

• clear clear all the items in the container

Page 23: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

#include <iostream>#include <vector>using namespace std;int main() { vector<int> 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 :

Page 24: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 24

#include <iostream>#include <vector>using namespace std;int main() { vector<int> 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=> -11 5 3 2

output:

return the size

Demonstrate that you do not need to worry about memory allocating for it :

Page 25: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 25

int main() { vector<int> 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 = 2size = 5size = 35 1 3

output:

Demonstrate that the vector class will automatically increase its internal storage capacity when required :

remove item from end

Page 26: Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.

Computer Programming II 26

int main() { vector<string> 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=> quitshoheldominicangelinebllawnorhanaazzyati

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.