Templates and Generic Programming Note
Templates and Generic Programming Note
Template is a new concept that enables us to define generic classes and functions
and thus provides support for generic programming.
A template can be used to create family of classes or functions.for eg:a class
templates for an array class would enable us to create arrays of various data types
om
such as int array or float array or char array.
Generic programming is an approach where generic types are used as parameters
in algorithms so that they work for a variety of suitable data types and data
.c
structures.
t
po
Advantages and Disadvantages of using templates
Advantages: gs
lo
Class Template can handle different types of parameters.
A template can be used to create family of classes or functions.
.b
Templates reduce the effort on coding for different data types to a single set
of code.
Testing and debugging efforts are reduced.
ew
Disadvantages:
od
Types of Template
There are basically two types of template.They are:
om
values.
.c
General Format
t
po
template<class T>
return-type function-name(argument list of type T){
//body of the function with type T gs
lo
}
.b
Eg:WAP to calculate the sum of two integers and two float values using function
template.
eb
Ans: #include<iostream>
ew
return (x+y);
m
}
main(){
int a=2,d=3;
float b=2.3,c=6.2;
cout<<"sum of int and int values="<<add(a,d)<<endl;
om
Ans: #include <iostream>
using namespace std;
.c
template <class T>
t
po
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2; gs
lo
}
.b
int main()
{
eb
cout <<" larger value among two integers."<< Large(i1, i2) << endl;
cout << "Enter two floating-point numbers:";
m
om
void swapp(T &x,T &y){
T temp;
.c
temp=x;
t
po
x=y;
y=temp;
} gs
lo
main(){
.b
int a=100,b=200;
float c=100.2,d=98.6;
eb
swapp(a,b);
ew
}
Q4)Write a function template to find average and multiplication of numbers.
m
Ans: #include<iostream>
using namespace std;
template <class T>
void calculate(T x,T y){
T s;
4 Compiled by Er.Shraddha Parajuli
s=(x+y)/2;
cout<<"average of two numbers="<<s;
T m;
m=x*y;
om
cout<<"multiplication of two numbers="<<m;
}
.c
main(){
t
po
int a=2, b=3;
calculate(a,b);
} gs
lo
Q4)WAP to find the maximum among the elements of an integer array having 6
.b
template<class T>
T min(T a[], int n)
od
{
dc
int i, j;
T temp=a[0];
m
for(i=0;i<n;i++)
{
if(a[i]>temp)
temp=a[i];
}
5 Compiled by Er.Shraddha Parajuli
return temp;
}
main()
{
int min1;
om
float min2;
int a[6]={5,2,1,3,4,0};
.c
float b[4]={1.2,8.3,6.7,1.1};
t
po
min1= min(a,6);
cout<<"\nminimum of integer array: "<<min1;
min2=min(b,4); gs
lo
cout<<"\nminimum of float array: "<<min2;
.b
return 0;
eb
#include<iostream>
od
{
int i, j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
om
a[i] = a[j];
a[j] = temp;
.c
}
t
po
}
}
} gs
lo
.b
main()
eb
{
int i;
ew
int a[6]={5,2,1,3,4,0};
od
float b[4]={1.2,8.3,6.7,1.1};
bubble(a,6);
dc
for( i=0;i<6;i++)
{
cout<<a[i]<<"\t";
}
bubble(b,4);
om
}
b)Function template with multiple parameters(i.e. function with different generic
.c
types):
t
po
We can use more than one generic data type in template statement,using a
comma-separated list.i.e.
General Format
template<class T,class T2,……..>
gs
lo
return-type function-name(argument of types T1,T2,….){
.b
//body of function
eb
}
ew
cout<<"sum="<<x+y;
}
main(){
int a=2,d=3;
float b=2.3,c=6.2;
om
function template.
Ans: #include <iostream>
.c
using namespace std;
t
po
template <class T1,class T2>
void Large(T1 n1, T2 n2)
{ gs
lo
if(n1>n2)
.b
cout<<"largest is:"<<n1;
else
eb
cout<<"largest is:"<<n2;
ew
}
int main()
od
{
dc
om
Eg:Bubble sorting using nesting of function template
#include<iostream>
.c
using namespace std;
t
po
template<class T>
void bubble(T a[], int n)
{ gs
lo
int i, j;
.b
for(i=0;i<n-1;i++)
eb
{
for(j=i+1;j<n;j++)
ew
{
od
if(a[i]>a[j])
{
dc
swap(a[i],a[j]);
m
}
}
}
}
template<class X>
om
}
main()
.c
{
t
po
int i;
int a[6]={5,2,1,3,4,0};
float b[4]={1.2,8.3,6.7,1.1}; gs
lo
bubble(a,6);
.b
for( i=0;i<6;i++)
cout<<a[i]<<"\t";
ew
bubble(b,4);
od
cout<<b[i]<<"\t";
m
return 0;
}
om
}
template<class T,class T1>
.c
void display(T x,T1 y){
t
po
cout<<"value of x1="<<x<<"value of y1="<<y;
}
void display(int x){ gs
lo
cout<<"value of normal function x="<<x;
.b
}
eb
main(){
display(100);
ew
display(12.2);
od
display(12,13.4);
dc
}
m
Output:
Value of normal function x=100
Value of template function x=12.2
Value of x=12,y=13.4
om
//class member specifications with type T
}
.c
The class template is very similar to the ordinary class definition except the prefix
t
po
template<class T> and the use of T.This prefix tells the compiler that we are going
to declare a template and use T as a typename in the declaration.
gs
A class created from a class template is called a template class.The syntax for
declaring an object of template class is:
lo
Class-name<type>object-name;
.b
instantiation.
Syntax for defining the member function of class template outside the class:
ew
template<class T>
od
}
m
Eg:WAP to calculate the sum of two integers and two float values using class
template.
Ans: #include<iostream>
using namespace std;
template<class T>
class demo{
13 Compiled by Er.Shraddha Parajuli
T x,y;
public:
demo(T a,T b){
x=a;
y=b;
om
}
void display(){
.c
cout<<"sum="<<x+y;
t
po
}
};
main(){ gs
lo
demo<int>d1(1,2);
.b
d1.display();
eb
demo<float>d2(2.2,3.2);
d2.display();
ew
}
od
Q1)WAP to find out the greatest among the two integer values and two float
dc
om
cout<<"greatest="<<(x>y?x:y);
}
.c
};
t
po
main(){
demo<int>d1(1,2);
d1.display(); gs
lo
demo<float>d2(2.2,3.2);
.b
d2.display();
eb
}
Q2)WAP to find the scalar product of two vectors in which both vector are of int
ew
type.
Ans: First Method:
od
#include<iostream>
dc
template<class T>
class vector{
T *v;
public:
vector(){
15 Compiled by Er.Shraddha Parajuli
v=new T[size];
for(i=0;i<size;i++){
v[i]=0;
}
}
om
vector(T a[]){
for(i=0;i<size;i++){
.c
v[i]=a[i];
t
po
}
}
T operator *(vector y){ gs
lo
T sum=0;
.b
for(i=0;i<size;i++){
eb
sum+=v[i]*y.v[i];
}
ew
return sum;
od
}
void display(){
dc
for(i=0;i<size;i++){
m
cout<<v[i]<<" ";
}
}
};
main(){
om
v2=y;
v1.display();
.c
v2.display();
t
po
cout<<"scalar product of two vector i.e v1*v2="<<v1*v2;;
} gs
lo
OR Second Method:
.b
#include<iostream>
eb
class scalar{
od
T a,b,c;
public:
dc
scalar(){
m
}
scalar(T x,T y,T z){
a=x;
b=y;
om
return temp;
.c
}
t
po
void display(){
cout<<a<<"i+"<<b<<"j+"<<c<<"k"<<endl;
} gs
lo
};
.b
main(){
eb
int s3;
scalar<int>s1(1,2,3);
ew
s1.display();
od
scalar<int>s2(2,3,4);
s2.display();
dc
s3=s1*s2;
m
cout<<"scalar product="<<s3;
}
Q3)WAP to find the scalar product of two float type vectors using class template.
Ans: #include<iostream>
using namespace std;
om
vector(){
v=new T[size];
.c
for(i=0;i<size;i++){
t
po
v[i]=0;
}
} gs
lo
vector(T a[]){
.b
v=new T[size];
eb
for(i=0;i<size;i++){
v[i]=a[i];
ew
}
od
}
T operator *(vector y){
dc
T sum=0;
m
for(i=0;i<size;i++){
sum+=v[i]*y.v[i];
}
return sum;
}
om
};
main(){
.c
float x[3]={1,2,3};
t
po
float y[3]={4,5,6};
vector<float>v1;
vector<float>v2; gs
lo
v1=x;
.b
v2=y;
eb
v1.display();
v2.display();
ew
}
Q)A program to push and pop element in a stack using class template.
dc
Ans: #include<iostream>
m
om
}
void push(T data){
.c
if(top==(max-1)){
t
po
cout<<"stack is full";
}
else{ gs
lo
top++;
.b
stk[top]=data;
eb
}
}
ew
void pop(){
od
if(top==-1){
cout<<"stack is empty";
dc
}
m
else{
top--;
}
}
void show(){
om
main(){
stack<int>s;
.c
s.push(1);
t
po
s.push(2);
s.push(3);
s.push(4); gs
lo
s.push(5);
.b
s.show();
eb
s.pop();
s.show();
ew
}
od
We can use more than one generic data types in a class template.
m
om
T1 a;
T2 b;
.c
public:
t
po
demo(T1 x,T2 y){
a=x;
b=y; gs
lo
}
.b
void display(){
eb
cout<<"sum="<<a+b;
}
ew
};
od
main(){
int a,b;
dc
float c,d;
m
om
**Using default type in a class template**
Eg: #include<iostream>
.c
using namespace std;
t
po
template<class T1=int,class T2=int>
class demo{
T1 a; gs
lo
T2 b;
.b
public:
eb
b=y;
od
}
void display(){
dc
cout<<"sum="<<a+b;
m
}
};
main(){
int a=2,b=5;
float c=1.1,d=2.2;
om
obj3.display();
demo<float>obj4(c,a);
.c
obj4.display();
t
po
}
Output:
Sum=3 gs
lo
Sum=7.2
.b
Sum=3
eb
Sum=3.1
ew
Exception Handling
od
Problems other than the logic and syntax error is exception.Exception is defined
as the run time anomalies or unusual conditions that a program may encounter
dc
Types of exception
There are two types of exception as listed below:
om
Exception handling mechanism includes following steps:
1. Find the problem(Hit the exception)
.c
2. Inform that the error has occurred(throw the exception)
t
3. Receive the error information(catch the exception)
po
4. Take corrective action(handle the exception)
gs
Exception handling/Error handling mechanism contains two segments:
1. To detect errors and to throw the exceptions.
lo
2. To catch the exceptions and take appropriate actions.
.b
This mechanism is basically built upon three keywords namely try,throw and
catch.The block of statements that may generate the exceptions are included
ew
om
exception entity
t .c
po
Catch block
Catches and ha
ndles the excep
tion
gs
lo
.b
try{
…….
ew
throw (exception)
…….
od
…….}
catch(type argument){
dc
……
…..}
m
When the try block throws an exception,the program control leaves the try
block and enters the catch statement of the catch block.
Note:::
The exception are the objects used to transmit information about a
problem.If the type of the object thrown matches the argument type in the
catch statement then catch block is executed for handling the exception.If
When the exception is detected and thrown ,the control goes to statement
immediately after the catch block.
Eg:main(){
om
int a,b,x;
cout<<”enter a and b:”;
.c
cin>>a>>b;
x=a-b;
t
po
try{
if(x!=0)
{
cout<<”result=”<<a/x;
}
gs
lo
else{
.b
throw(x);
}
eb
}
catch(int i){
ew
}
dc
Most often the exceptions are thrown by functions that are from within try
blocks.The point at which throw is executed is called the throw point.
m
om
void divide (int x,int y,int z)
{
.c
if((x-y)!=0){
cout<<”result=”<<z/(x-y);
t
po
}
else{
throw (x-y);
}
}
gs
lo
main(){
.b
try{
divide(10,20,30);
eb
divide(10,10,20);
}
ew
catch(int i){
cout<<”caught an exception”;
od
}
}
dc
om
//catch blockN
}
.c
When an exception is thrown the catch block is searched in order for an
appropriate match.The first handler that yields a match is executed .After
t
po
executing the handler block(i.e. catch),the control goes to the first statement
after the last catch block for that try(in other words,all other handlers are
skipped).When no match is found ,program is terminated.
Eg: gs
lo
void test(int x){
.b
try{
eb
if(x==1)
throw x;
ew
else if(x==0)
od
throw ‘x’;
else
dc
throw 1.2;
m
}
catch(int m){
cout<<”caught an integer”;
}
Catch(char c){
om
}
main(){
.c
cout<<”testing multiple catches:”;
t
po
test(1);
test(0);
test(-1); gs
lo
}
.b
eb
Rethrowing an exception
ew
A catch block can also decide to rethrow the exception caught without processing
it.In such situations we may simply invoke throw without any arguments as shown
below:
od
try{
If(y==0.0)
m
throw y;
else
cout<<”division:”<<x/y;
}
catch(float a){
om
try{
divide(10.5,2.0);
.c
divide(20.0,0.0);
t
po
}
catch(float b){
cout<<”caught exception”; gs
lo
}
.b
}
eb
When an exception is rethrown ,it will not be caught by the same catch statement
or any other catch in that group.Rather,it will be caught by an appropriate catch in
ew
Components of STL
1. Containers
2. Algorithms
3. Iterators
Iterator 1 Iterator 2
Object1
om
.c
Object2 object3
t
po
Iterator 3
gs
lo
.b
algorithm
3
eb
therefore can be easily customized to hold different types of data.The STL defines
10 containers which are grouped into 3 categories as given below:
m
om
containers they are stack,queue,priority-queue.
2)Algorithms:Algorithms are functions that can be used generally across a variety
.c
of containers for processing their contents.STL provides more than 60 standard
t
algorithms to support more extended or complex operations.It allows us to work
po
with two different type of containers at the same time.To access standard
algorithm we must include<algorithm>in our program.STL algorithms,based on the
gs
nature of operations they perform,it is categorized as:
Retrieve or nonmutating algorithms.
lo
Mutating algorithms
.b
Sorting algorithms
eb
Set algorithms
Relational algorithms
ew
performing certain actions.The input and output supports the least functions.They
can be used only to traverse in container.The forward iterator supports all the
functions of input and output and also retains its position in the container.A
m