Upload
aravind-k-r-kr
View
221
Download
0
Embed Size (px)
Citation preview
8/7/2019 New Templates
1/30
TEMPLATESTEMPLATES
Anas P.S21-Feb-2011
8/7/2019 New Templates
2/30
DefinitionDefinition
y Templates are mechanisms for generating
functions and classes based on typeparameters
y Also called type parameterization
Types are given as parameters to a template
Like variables are given as a functions parameters
y
Two typesFunction Templates And
Class Templates
8/7/2019 New Templates
3/30
Function TemplatesFunction Templates
Syntax:
template
function_declaration;
-Or-
template
function_declaration;
8/7/2019 New Templates
4/30
4
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 T min(T x[], int n){T m = x[0]; // M is the minimum so far
for (int i=1;i
8/7/2019 New Templates
5/30
How to Call a Function Template
functionName(parameter-list);
int x[]={11, 13, 5, 7, 4, 10};
double y[]={4.5, 7.13, 3, 17};int minx = min(x,6);
double miny=min(y,4);
cout
8/7/2019 New Templates
6/30
Function with two generic typesFunction with two generic types#include using namespace std;template void myfunc(type1 x, type2 y)
{cout
8/7/2019 New Templates
7/30
Class TemplatesClass Templates
template
class ClassName{
definition
};
Syntax:
Need not use "T", any identifier will work
To create an object of the class, typeClassName< type myObject;
Example:Stack< double >doubleStack;
8/7/2019 New Templates
8/30
Class Template(Example)Class Template(Example)
#include#include
using namespace std;templateclass Stack
{public:
Stack(){top = 0;}
~Stack(){};void push(StackT t);
void pop();
private:int top;StackT st[2];
};
templatevoidStack::push(StackT a)
{if(top>1){
cout
8/7/2019 New Templates
9/30
Class Template(Example)Class Template(Example)
continuescontinuestemplatevoid Stack::pop(){
if((top)
8/7/2019 New Templates
10/30
Output is:Output is:void main(){
Stack c;c.push(1);
c.push(2);c.push(3);
c.pop();c.pop();c.pop();
Stack c1;c1.push('a');c1.push('b');c1.push('c');
c1.pop();c1.pop();
c1.pop();
}
Index: 0 1Index: 1 2
Stack FullPoped Element is : 2Poped Element is : 1Nothing to pop
Index: 0 aIndex: 1 b
Stack FullPoped Element is : bPoped Element is : aNothing to pop
8/7/2019 New Templates
11/30
Class templates ContinuesClass templates ContinuesThe declarations and definitions need to be in the same header file
//B.Htemplate class b{
public:b() ;
~b() ;} ;
// B.CPP#include "B.H"template b::b() { }
template b::~b() { }
//MAIN.CPP#include "B.H"void main(){
b bi ;b bf ;
}
This wont compileReason:-When compiling B.cpp, the compiler has both the declarations andthe definitions available. When the compiler compiles main.cpp has the
declarations but no definitions
8/7/2019 New Templates
12/30
SolutionSolution
y The first solution is to physically move
the definition of the template functioninto the .h file,
//B.Htemplate class b{
public:b() ;
~b() ;} ;
template b::b() { }template b::~b() { }
//MAIN.CPP#include "B.H"void main(){
b bi ;b bf ;
}
8/7/2019 New Templates
13/30
Solution continuesSolution continues
y The other solution is to leave the
definition of the template function in the.cpp file and simply add the line template
template b; to that file:
//B.Htemplate class b{
public:b() ;
~b() ;} ;
// B.CPP#include "B.H"template b::b() { }
template b::~b() { }
template b;
//MAIN.CPP#include "B.H"void main(){
b bi ;b bf ;
}
8/7/2019 New Templates
14/30
STL(Standard Template Library)STL(Standard Template Library)
y The Standard Template Libraries (STL's) are a set of C++ templateclasses to provide common programming data structures and functionssuch as doubly linked lists (list), paired arrays (map), expandable arrays
(vector), large string storage and manipulation (rope), etc.
y The standard library is defined in a namespace called std and is
presented as a set of headers.y For using a particular container, you need to include the corresponding
headers in your program.
y Since the STL classes are part of the std namespace, you will need to
either prefix every container class type with "std::.#include
std::vector myIntVector; or include "using namespace std;" at the beginning of the code.#include
using namespace std;
vector myIntVector;
8/7/2019 New Templates
15/30
Some DefinitionsSome Definitionsy The standard template library (STL) contains
Containers
Algorithms
Iterators
Containers:A container is a way that stored data is organized in memory, forexample an array of elements.
Eg: an array of elements
Algorithms: Algorithms in the STL are procedures that are applied tocontainers to process their data
Eg:search for an element in an array, or sort an array. You can reversethe order of elements in a vector
Iterators: Generalization of pointers,used to traverse the objects stored in a
containerEg: you can increment an iterator to point to the next element in an array
8/7/2019 New Templates
16/30
y Algorithms use iterators to interact with
objects stored in containers
Algorithm
Iterator
Iterator
Algorithm
Iterator
Iterator
Algorithm
8/7/2019 New Templates
17/30
Container TypesContainer Types
y The STL provides several basic kinds ofcontainers
: one-dimensional array
: double linked list : double-ended queue
: queue
: stack
: set : associative array
8/7/2019 New Templates
18/30
8/7/2019 New Templates
19/30
VectorVector
y A vector is a Sequence that supports random access to elements,constant time insertion and removal of elements at the end, andlinear time insertion and removal of elements at the beginning or inthe middle.
y The number of elements in a vector may vary dynamically; memorymanagement is automatic.
y Vector is the simplest of the STL container classes, and in manycases the most efficient.
y #include
8/7/2019 New Templates
20/30
Syntax: vectorFor example : vector - vector of integers.
vector - vector of strings.vector - vector of pointers to integers.vector - vector of pointers to
CMyClass objects.
Construction: A vector can be initialized by specifying itssize and
a prototype element or by another vector
vector
v1(1000); // creates vector of size 1000,// requires default constructor for
Vector Continues.Vector Continues.
8/7/2019 New Templates
21/30
ExampleExample
void example(){
const int nSize = 10;vector vecEgs(nSize );
// initialize vec.vecEgs[0] = 1;int nEgArr [nSize ];
for( int nCount = 0; nCount > word;
svec.push_back(word);//ok
if (svec.at(3) == aaa) //error..exception
string strNew = svec[3]; //error..exception
8/7/2019 New Templates
23/30
InsertionInsertion
vector vecEgspush_back
vecEgs.push_back(10);//inserts at end
InsertvecEgs.insert(vecEgs.begin() , 10) ; //inserts ata posvecEgs.insert(pos,n,10) //inserts n elementsat a posThis is equal tofor (int nCnt = 0;nCnt < n ;++ nCnt)
vecEgs.insert(pos, 10)
8/7/2019 New Templates
24/30
DeletionDeletion
y erase erase at any position -
vecEgs.erase (pos)
Basic operations Pop_back removesone from end
8/7/2019 New Templates
25/30
Points to notePoints to note
y Insertion at the back of a vector is efficient.y The vector simply grows, if necessary, to
accommodate the new item.y It is expensive to insert (or delete) an element in
the middle of a vector the entire portion of thevector after the insertion (or deletion) pointmust be moved, because vector elements occupycontiguous cells in memory
y It is faster to insert many elements at once than
one at a timey Use const iterators if you dont need to modify
the elements
8/7/2019 New Templates
26/30
ListList
y Provide linear time access to asequence of varying length withconstant time insertions and
deletions at any position
8/7/2019 New Templates
27/30
ExampleExampley #include
y #include
y #include
y #include
y using namespace std;
y void main()
y {y list li;
y li.push_back(100);
y li.push_back(200);
y li.push_front(90);
y list::iterator it;
y for(it=li.begin();it!=li.end();it++)
y {
y cout
8/7/2019 New Templates
28/30
DequeDeque
y Provide random access to a sequence of
varying length with constant timeinsertions and deletions at both beginning
and the end
8/7/2019 New Templates
29/30
ExampleExampley #include
y #include
y #include
y #include
y using namespace std;
y void main()
y {y deque li;
y li.push_back(100);
y li.push_back(200);
y li.push_front(90);
y li.pop_front();
y deque::iterator it;
y for(it=li.begin();it!=li.end();it++)
y {
y cout
8/7/2019 New Templates
30/30
vector Deque list
Insertionand
deletion
Efficient atthe end
pos
Efficient atthe end
and start
Efficientat any
position
Random
Access
YES YES NO
iterator Deletioninvalidatespastelements
Invalidatealliterators
Invalidate onlythedeleted
one