[09.04.2010] Templates and Standard Template Library
Unix C++ :: UNIX CPP :: CPP :: Case Studies
Page 1 of 1
[09.04.2010] Templates and Standard Template Library
Today's agenda is Templates and STL. If u have any queries regarding Templates or STL, post ur queries. I ll post some example pgms soon.
FUNCTION TEMPLATES
PROGRAM TO FIND MINIMUM AND MAXIMUM VALUE IN AN ARRAY
- Code:
#include<iostream.h>
// Minimum in Array
template<class A>
A minInArray(A *a,int size)
{
A small=a[0];
for(int i=0;i<size;i++)
{
if(a[i]<small)
small=a[i];
}
return small;
}
//Maximum in Array
template<class A>
A maxInArray(A *a,int size)
{
A big=a[0];
for(int i=0;i<size;i++)
{
if(a[i]>big)
big=a[i];
}
return big;
}
int main()
{
int d[6]={6,8,4,3,7,9};
cout<<endl<<minInArray(d,6)<<endl;
cout<<endl<<maxInArray(d,6)<<endl;
}
CLASS TEMPLATES
PROGRAM TO MULTIPLY 2 VECTORS USING CLASS TEMPLATES
- Code:
#include<iostream.h>
#include<vector.h>
#include<iomanip.h>
#include<iterator.h>
template<class B>
class Sample
{
vector<B> values;
public:
Sample()
{
}
Sample(int size)
{
int temp;
cout<<"Enter "<<size<<" Values : ";
for(int i=0;i<size;i++)
{
cin>>temp;
values.push_back(temp);
}
}
Sample operator *(Sample &s)
{
typename vector<B>::const_iterator i,j;
Sample a;
for(i=values.begin(),j=s.values.begin();i!=values.end();i++,j++)
{
a.values.push_back((*i)*(*j));
}
return a;
}
void disp()
{
typename vector<B>::const_iterator i;
for(i=values.begin();i!=values.end();i++)
{
cout<<" "<<*i;
}
}
};
int main()
{
Sample<int> a(5),b(5),c;
c=a*b;
c.disp();
}
Unix C++ :: UNIX CPP :: CPP :: Case Studies
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|