Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

TEMPLATES

Anas P.S
21-Feb-2011
Definition
Templates are mechanisms for generating
functions and classes based on type
parameters
Also called “type parameterization”
◦ Types are given as parameters to a template
◦ Like variables are given as a function’s parameters
Two types
Function Templates And
Class Templates
Function Templates
Syntax:
template<class type> function_declaration;
-Or-
template<typename type>
function_declaration;
Templates of Functions (Example)
// Precondition: x[] is an array of length n, of
// a generic type. n is a positive integer.
// Postcondition: the output is the minimum in x[]
template<typename T> T min(T x[], int n){
T m = x[0]; // M is the minimum so far
for (int i=1;i<n;i++)
if (x[i]<m)
m=x[i];
return m;
}
4
How to Call a Function Template
functionName<an-actual-type>(parameter-list);

int x[]={11, 13, 5, 7, 4, 10};


double y[]={4.5, 7.13, 3, 17};
int minx = min<int>(x,6);
double miny=min<double>(y,4);
cout<<“the minimum of array x is: “<<minx<<endl;
cout<<“the minimum of array y is: “<<miny<<endl
Function with two generic types
#include <iostream>
using namespace std;
template <class type1, class type2>
void myfunc(type1 x, type2 y)
{
cout << x << ' ' << y << '\n';
}
int main()
{
myfunc(10, "I like C++");
myfunc(98.6, 19L);
return 0;
}
type1 and type2 are replaced by the compiler
with the data types int and char *, and double and long,
respectively,
Class Templates
Syntax:
template <class T>
class ClassName{
definition
};

Need not use "T", any identifier will work


To create an object of the class, type
ClassName< type myObject;
Example: Stack< double > doubleStack;
Class Template(Example)
#include<stdafx.h> template<class StackT>void
#include<iostream> Stack<StackT>::push(StackT a)
using namespace std; {
template<class StackT> if(top>1)
class Stack {
{ cout<<"stack full"<<endl;
public: }
Stack(){top = 0;} else
~Stack(){}; {
void push(StackT t); cout<<"index: "<<top<<"";
void pop(); st[top] = a;
private: cout<<st[top]<<endl;;
int top; top++;
StackT st[2]; }
}; }
Class Template(Example) continues…
template<class StackT>void Stack<StackT>::pop()
{
if((top) <= 0)
{
cout<<"nothing to pop“ << endl;
}
else
{
top--;
cout<<"element poped is "<<st[top]<<endl;
}

}
Output is:
void main() Stack<char> c1;
{ c1.push('a');
Stack<int> c; c1.push('b');
c.push(1); c1.push('c');
c.push(2); c1.pop();
c.push(3); c1.pop();
c.pop(); c1.pop();
c.pop();
c.pop();
}

Index: 0 1 Index: 0 a
Index: 1 2 Index: 1 b
Stack Full Stack Full
Poped Element is : 2 Poped Element is : b
Poped Element is : 1 Poped Element is : a
Nothing to pop Nothing to pop
Class templates Continues……
The declarations and definitions need to be in the same header file

//B.H // B.CPP //MAIN.CPP


template <class t> #include "B.H" #include "B.H"
class b template <class t> void main()
{ b<t>::b() { } {
public: template <class t> b<int> bi ;
b() ; b<t>::~b() { } b <float> bf ;
~b() ; }
};

This won’t compile


Reason:-When compiling B.cpp, the compiler has both the declarations and
the definitions available. When the compiler compiles main.cpp has the
declarations but no definitions
Solution
The first solution is to physically move
the definition of the template function into
the .h file,
//B.H //MAIN.CPP
template <class t> #include "B.H"
class b void main()
{ {
public: b<int> bi ;
b() ; b <float> bf ;
~b() ; }
};
template <class t> b<t>::b() { }
template <class t> b<t>::~b() { }
Solution continues…………
The other solution is to leave the
definition of the template function in
the .cpp file and simply add the line
template template b<int>; to that file:
//B.H // B.CPP //MAIN.CPP
template <class t> #include "B.H" #include "B.H"
class b template <class t> void main()
{ b<t>::b() { } {
public: template <class t> b<int> bi ;
b() ; b<t>::~b() { } b <float> bf ;
~b() ; template b<int>; }
};
STL(Standard Template Library)
 The Standard Template Libraries (STL's) are a set of C++ template
classes to provide common programming data structures and functions
such as doubly linked lists (list), paired arrays (map), expandable
arrays (vector), large string storage and manipulation (rope), etc.
 The standard library is defined in a namespace called std and is
presented as a set of headers.
 For using a particular container, you need to include the corresponding
headers in your program.
 Since the STL classes are part of the std namespace, you will need to
◦ either prefix every container class type with "std::“.
#include <vector>
std::vector<int> myIntVector;
◦ or include "using namespace std;" at the beginning of the code.
#include <vector>
using namespace std;
vector<int> myIntVector;
Some Definitions
 The standard template library (STL) contains
◦ Containers
◦ Algorithms
◦ Iterators
Containers: A container is a way that stored data is organized in memory, for
example an array of elements.
Eg: an array of elements
Algorithms: Algorithms in the STL are procedures that are applied to
containers to process their data
Eg: search for an element in an array, or sort an array. You can reverse the
order of elements in a vector
Iterators: Generalization of pointers,used to traverse the objects stored in a
container
Eg: you can increment an iterator to point to the next element in an array
Algorithms use iterators to interact with
objects stored in containers

Iterator
Algorithm

Iterator

Algorithm
Iterator
Iterator

Algorithm
Container Types
The STL provides several basic kinds of
containers
◦ <vector> : one-dimensional array
◦ <list> : double linked list
◦ <deque> : double-ended queue
◦ <queue> : queue
◦ <stack> : stack
◦ <set> : set
◦ <map> : associative array
Container Categories
 Sequence Containers
Organize collection of objects,into a strictly linear
arrangement
◦ Egs: vector, deque, list
 Sorted Associative Containers
Provide fast retrieval of objects from the collection based
on keys
◦ Egs: set, multiset, map, multimap
 Adapters
Inherit from the two first-class containers and modify their
interfaces.
◦ Three major types:- stack, queue, priority queues
Vector
 A vector is a Sequence that supports random access to elements,
constant time insertion and removal of elements at the end, and
linear time insertion and removal of elements at the beginning or in
the middle.
 The number of elements in a vector may vary dynamically;
memory management is automatic.
 Vector is the simplest of the STL container classes, and in many
cases the most efficient.
 #include <vector>
Vector Continues….
Syntax: vector<of what>
For example : vector<int> - vector of integers.
vector<string> - vector of strings.
vector<int *> - vector of pointers to integers.
vector<CMyClass*> - vector of pointers to CMyClass
objects.
Construction: A vector can be initialized by specifying its size
and
a prototype element or by another vector
vector<Date> v1(1000); // creates vector of size 1000,
// requires default constructor for
Example
void example()
{
const int nSize = 10;
vector<int> vecEgs(nSize );
// initialize vec.
vecEgs[0] = 1;
int nEgArr [nSize ];

for ( int nCount = 0; nCount < nSize;


nCount ++ )
nEgArr[nCount ] = vecEgs[nCount ];
}
Example
vector<string> svec;
we insert elements, rather than index and assign.
string word;
cin >> word;
svec.push_back(word);//ok

if (svec.at(3) == “aaa”) //error..exception


string strNew = svec[3]; //error..exception
Insertion
vector<int> vecEgs
push_back
vecEgs.push_back(10);//inserts at end
Insert
vecEgs.insert(vecEgs.begin() , 10) ; //inserts at a
pos
vecEgs.insert(pos,n,10) //inserts n elements at a pos
This is equal to
for (int nCnt = 0;nCnt < n ;++ nCnt)
vecEgs.insert(pos, 10)
Deletion
erase – erase at any position -
vecEgs.erase (pos)
Basic operations Pop_back – removes one
from end
Points to note
Insertion at the back of a vector is efficient.
The vector simply grows, if necessary, to accommodate
the new item.
It is expensive to insert (or delete) an element in the
middle of a vector the entire portion of the vector after
the insertion (or deletion) point must be moved, because
vector elements occupy contiguous cells in memory
It is faster to insert many elements at once than one at a
time
Use const iterators if you don’t need to modify the
elements
List
Provide linear time access to a
sequence of varying length with
constant time insertions and
deletions at any position
Example
#include<stdafx.h>
#include<iostream>
#include<list>
#include<iterator>
usingnamespace std;
void main()
{
 list<int> li;
 li.push_back(100);
 li.push_back(200);
 li.push_front(90);
 list<int>::iterator it;
 for(it=li.begin();it!=li.end();it++)
 {
 cout<<*it<<endl;
 }
}
Deque
Provide random access to a sequence of
varying length with constant time
insertions and deletions at both beginning
and the end
Example
#include<stdafx.h>
#include<iostream>
#include<deque>
#include<iterator>
using namespace std;
void main()
{
 deque<int> li;
 li.push_back(100);
 li.push_back(200);
 li.push_front(90);
 li.pop_front();
 deque<int>::iterator it;
 for(it=li.begin();it!=li.end();it++)
 {
 cout<<*it<<endl;
 }
}
vector Deque list
Insertion Efficient at Efficient at Efficient
and the end the end at any
deletion pos and start position
Random YES YES NO
Access
iterator Deletion Invalidate Invalidat
invalidates all e only
past iterators the
elements deleted
one

You might also like