- Shery khan
Download
Report
Transcript - Shery khan
TEMPLATES
Lecture 32-45
Presented By
SHERY KHAN
Object Orienting Programming
Agenda
Templates
User Specialization
User Define Types
Class Templates
Member Templates
Partial Specialization
Complete Specialization
Non Type Parameters/Default Type Parameter
Resolution Order/Template & Friends
Template and Static Members
Cursors
Iterator
Standard Template Library
TEMPLATES
C++ More Power full Feature ,namely Templates .
Templates Enable Us to specify with single code
segments an entire Range of related (overloaded
function called TEMPLATE FUNCTION
Or Entire Range of related Classes –Called Template
Classes
Advantages:
We might write a single Function for any Problem
and use it with different Data types
:int,float,char,string
Generic Concept
Generic Programming refers to program
containing generic abstraction
If we have same logic like print some numbers
whether they have different data types we can
draw a Algorithm that is Generic and used
with different Data type
Advantages
REUSEABILTY :code can Work for all data
type
Writ ability : Lesser Time to write
Maintainability: Change in one Function so
increase Maintainability
Distinction B/w Function Template
& Template Function
Function Templates and class templates are
like stencil out of which we trace shapes.
Function templates can be parameterized to
operate on different data type.
Template Function and template classes are
like the separate tracing that all have the Same
Shapes but could be drawn in different colors
FUNCTION TEMPLATES
OVERLOADED FUNCTION:
Are normally used to perform Similar
Operation on Different Data Types
FUNCTION TEMPLATES:
If Operation are Identical for Each type this
may be performed more compactly and
Conveniently using Function Templates
continue
The programmer writes a Single Function
template Definition based on the Arguments
provided in calls to this function the complier
automatically generate a separate object code
function to handle Each type of Call
Appropriately
NOTE!!!!
:::::C this Task was done by Macros but they
donot care about Type Checking
Declaration Function Template
All function Template begin with Keyword
template followed by list of Parameters
to function template enclosed in angel
brackets
template<class t>
Or
template<class A,class B>
template<class Element Type>
continue
In Above Declaration T is type name of class
name and we use this T instead of data type for
which we want our function to work as
template.
Example
Let us examine the pA function template this
template is used in Complete program
Program TEMPlATE
#include<iostream.h>
template<class T>…………………
void pA( T *array, int count)
{
for(int i=0;i<count;i++)
cout<<array[i]<<",";
cout<<endl;
}
Program Main part
int main()
{
const int account=5,bcount=4,ccount=6,fcount=3; // Declaring Size of
Array
int a[acount]={1,2,3,4,5};
double b[bcount]={1.1, 2.2, 3.3, 4.4};
float f[fcount]={24.26,56.56,8989.26};
char c[ccount]="ABC";
pA(a,acount);
pA(b,bcount);
pA(c,ccount);
pA(f,fcount);
system("pause");
}
OUT PUT
You see for int ,double,char,float
one function template is used
Explicit Type Parameterization:
In case the Function template does not have
any parameter then we have to explicit
mention the data type .
template<typename T>
T get input()
T x;
cin>>x;
return x;
int main()
int x;
x=getinput<int>();
double y;
y=getinput<double>();
Note :x=getinput(); // ERROR !!!!
Explicit
data type
User Define Specialization
A template Compiler Generated code may not
handle all the types successfully in this case
we give a explicit specialization for particular
data type.
For this purpose we give our own correct
specialization code
USER SPECIALIZATION
Some time our template is cant handle a all
data types for this purpose we do user
specialization for this appropriate type
template<typename T>
bool isEqual( T x,T y)
return(x==y);
Failure
IsEqual(“abc”,”xyz”)
This code is fail can return Logical Error !!!
Because of our implementation is x==y
Complier Translate it is
Return (char*==char*) OR
return(char[]=char[]);
Array consist of many element so comparison of array
is not Possible it will simple compare first element
What should we do?
We do User specialization
The code is below
Template<>
bool isEqual <const char*>
Const char*x,const char*y)
{
Return (strcmp(x,y)==0);
}
PAPERS
Q: Write the names of two types of Templates. MARKS: 2
Answer:- (Page 256)
a. Function Templates (in case we want to write general function like print Array)
b. Class Templates (in case we want to write general class like Array class)
Which of the following is the best approach if it is required to have more than one functions
having exactly same functionality and implemented on different data types?
► Templates (Page 256)
► Overloading
► Data hiding
► Encapsulation
Multiple Type Argument
For Conversion of Int to float or other data
type conversion we use two type argument
templates advantage is decrease the required
no of functions because the only one Generic
template is Write and use it for conversion
Multiple Type Argument
Syntax
template<typename T,typename U>
T my_cast(U u){
return(T)u;// U is converted to T type;
Any Data type
you want to convert
}
Need to mention the Type
Int main(){
Double d =10.5674;
Int j=my_cast(d);//Error int i=my_cast<int >d
Overloading /Templates
Overloading: Similar Operation(Milta Julta)
For E.g : Plus complex, imag
Function Template: Identical Operation(Bilkul
Aik ha Exactly Same ho)
For E.g. Array implementation for different
Data Type we Use Function Template Because
they have Same Type
Papers
Give the pseudo code of non case sensitive comparison
function of string class. Answer:- (Page 263)
int caseSencompare( char* str1, char* str2 )
{ for (int i = 0; i < strlen( str1 ) && i < strlen( str2 );
++i)
if ( str1[i] != str2[i] )
return str1[i] - str2[i];
return strlen(str1) - strlen(str2); }
Paper
What do you know about function Template?
(Answer: Page 262) Function templates are used when we want to have exactly
identical operations on different data types in case of function templates we cannot
change implementation from data type to data type however we can specialize
implementation for a particular data type.
GENERIC ALGORITHM
We want a Implementation which is
Independent of Data Structure in pA we can
print a Array which is work fine for all data
Types Using Generic programming Concept
but now We want to Implement a Template
which is Type and Data Structure Independent
So best Generic Algorithm is that which is
independent of Both type and Data Structure.
CASE STUDY
Lecture 34
Discussion On Type Independence And
Data Structure Independence
Generic Algorithm
Independent of Container and Type
We have a Find Algorithm Find Simply a
Integer from Array we Do Step by Step
Operation on it and Explain All Step that Are
Done our Purpose is To make a Function Type
and data Structure Independent
FIND Program (non Generic
Funtion)
const int* find( const int* array, int _size, int x ) {
const int* p = array;
for (int i = 0; i < _size; i++) {
if ( *p == x )
return p;
p++;
}
return 0;
}
Explanation
First Step is To write it as Template so they can Work for All Data Type instead Integers .
In Above Code A array has a Parameter passing Named as Find and one Constant
Pointer passing and array is Int type and Size tell the How many Elements of Array
has and also a int X is passing which is to be Find in Array if x is present in array of
Int then return pointer if not return Null Character……
Return Type const int* //
Name of Function Find
Parameter const int*array // Array is Pointer to constant int
Size of Array : int_size
Found Element Int x // As a Third Parameter of Find Function
A Temporary pointer is Intailize with Starting Adress of the Array which is passed
as parameter
Type Indepandanant
template< typename T >// Making it Generic So this Notation is Used
T* find( T* array,int _size, const T& x ) // Return Type is Changed with T*
{ T* p = array; for (int i = 0; i < _size; i++) // Local Pointer is intialize toarr
{ if ( *p == x )
return p;
p++;
} // pointing to next element of Array used to Go for next Index
return 0;}
Explaination:First Step is Type Independent
Pervious is Int x Is passing as Call by Value but
Now we can Passing X as Reference Because we doing it
asTypeIndepandant So to avoid Array of Complex we use it
Const T & x Because User define data Type are Heavy so in this
point we just send reference so it can nt be chaged
Array and T* tell us that it is Array first Index Pointer
Size is Replaced !!!!
template< typename T >
T* find( T* array, T* beyond, const T& x ) {
T* p = array;
while ( p != beyond ) { // so by doing this we can just know the Last Element
Container so iteration is from First to last Element so don’t want to know how much size is
beyond is pointing to last next Element
if ( *p == x )
return p;
p++;
pass a pointer which is
of
}
return 0;
one location next
After array
instead of Passing
}
Size here in previous we know About Count that
how many member of Array Element
Return beyound
template< typename T >
T* find( T* array, T* beyond, const T& x )
{
T* p = array;
while ( p != beyond )
{
if ( *p == x )
By replacing return statement by Beyond so if
return p;
p++;
element is not found we will not check
the return value for Null we simply
check whether is pointing to some
value or it point to beyond pointer so if Nt
Found then pointer points to Beyound
}
return beyond;
}
Null pointer indicate that we using
Array because it tells us that All the
Array is Iterated so our mission is to
Data Structure Independence
Single Return Statement
template< typename T >
T* find( T* array, T* beyond, const T& x )
{
T* p = array;
while ( p != beyond && *p != x )
if pointer not go to Array End and
Current pointer pointing is not equal to the num which is to be Find check next element otherwise P is
pointing to which value is Returned
p++;
return p;
}
if p find Some point x then it will return otherwise it iterate till then it is pointing to
beyound and While false and we return p instead of two returns we have single return code is Simplified
Still Not Independent data Structure because the P* exist Array Exist
Generic Code
Now our code is so generic that it will work for all types of containers (data structures)
supporting two operations,
Increment operator (++) as we are incrementing value in this container (Next Element
Access)
Dereference operator (*) as we are getting value from container for comparison by
dereferencing ( Element Access)
Container : is Some Type of Structure Which Contain some Thing it contain one Element and
Many Element also
Array is one Concrete Example of An Homogenous Container because its all element of Same
Type
Vector
Queue
Limitation
that we will need to pass container pointers in this function this is against the concept of generic
programming so we simply remove pointer notation from our code,
template< typename P, typename T >
P find( P start, P beyond, const T& x ) //first Element and next to beyond
element
{
while ( start != beyond && *start != x )
//both referecnce are not Equal we
check
& start is Dereference
// getting Element
start++;
return start;
}
That’s Our target by seeing this Code the Underline Data Structure is Not
Defined or Independent of underline Data Structure without knowning Data
structure we implement it As Array ,Queue
Class Templates
A single Class template has a functionality to
operate on different data types
Reuse of Classes
Syntax
template<class T>class XYZ{}; or
Template<typename T>class XYZ{};
Class Template
A Vector class template can store data elements of different types, without templates, we need a separate
Vector class for each data type.
template< class T >
class Vector {
Tell that it is Parameterized Class which has a
Parmeter T Not necessary
int size;
T* ptr;
public:
Vector<T>( int = 10 ); //size
Vector<T>( const Vector< T >& );// Copy Constructor
~Vector<T>();
int getSize() const;
const Vector< T >& operator =(
const Vector< T >& );
T& operator []( int );
};
private:
INSTANCES
We can create this Vector class instance for int
or char data type as given
Vector<int>intVector
Vector<char>charVector
Vector Class is Parametrized class and will
always be instantiated for particular type only
Papers
What is the difference (if any) between the two types of function declarations?
template function_declaration;
template function_declaration;
Answer:- The format for declaring function templates with type parameters is:
template <class identifier> function_ declaration;
template <typename identifier> function_ declaration;
The only difference between both prototypes is the use of either the keyword class
or the keyword typename. Its use is indistinct, since both expressions have exactly
the same meaning and behave exactly the same way.
MEMBER TEMPLATES
A class or class Template can have Member
Function that Are Them Selves Member
Templates
We say that member function of template class
implicitly become Function Template
They work for Instances (int,char,float,double)
Some Situation we Need Explicit Template
Function
Continue
Some Time We need that class template
Member function Explicitly we want for some
other type Template (Hum Cha raha hain ka
who kisi Aur Type ka liya bhe Type ban Jaye)
It mean we Explicitly Member Function to be
a Member Template for some Other type
which has been given to that Class as a
parameter
Class Template Having Member Function
that Are themselves Member Template
template<typename T> class Complex {
T real, imag;// Data Member T Type
public:
// Complex<T>( T r, T im ) // Prviously Every Member Function is
Parametrized with <T> c++ in Declaration <T>Not used Compler Do it self
Complex( T r, T im ) : // Constructor Taking Two Argument R,im both have
Type T parametrized Type
real(r), imag(im) {} // Member intializer list we can Intilize the
Both the Members
// Complex<T>(const Complex<T>& c)
Complex(const Complex<T>& c) :// Copy Constructor Rule of thumb that
With name No use of Type But in Return Type or Parameter Fully Qualified name
is USed argument of Copy constructor is Const Complex and Reference C
real( c.real ), imag( c.imag ) {} // Intialize Data Member with
Member Intializer List
};
Main Function
int main() {
Complex< float > fc( 0, 0 );// Complex Class is Intantiated for Float
argument 0,0 that the real and img part is Set with 0,0
Complex< double > dc = fc; // Error
// in copy constructor the type is Double and argument which is Send is Float So
TYPE MISS MATCH and now there is Need we have a Overloaded Copy
Constructor one for double,float,int etc
fc is also a Object of Float which is Initialized with dc object which type is double
Here Error because the Complex Float and Complex Double Are two distinct types
Complier don’t know about type conversion in class there is no function which tells
that How to do conversion Compiler Cant DO Type Conversion Automatically
return 0;
}
Overloaded Copy constructor
We need different overloaded copy
constructor work is identical Existing object
Data member are put and intialize to new data
member
This Give us a Clue that Copy constructor
must be made a Function Template because
the parameter is Required type for Complex
float ,double,etc
Double Replaces the T
class Complex<double> {
double real, imag;
public:
Complex( double r, double im ) :
real(r), imag(im) {}
Complex(const Complex<double>& c) :
real( c.real ), imag( c.imag ) {}
…
};
Member Template
template<typename T> class Complex {
T real, imag;
public:
Complex( T r, T im ) :
real(r), imag(im) {}
template <typename U>
// this
copy constructor is now taking two template
parameters one implicit T copy constructor is changed
Explicitly Member template
U is different Type and T is Different Type They have two
Identifiers / parameter types
Complex(const Complex<U>& c) :
real( c.real ), imag( c.imag ) {}
…
};
Main (ok)
Complex< float > fc( 0, 0 );//
Complex< double > dc = fc;// OKAY FINE
We are creating a new object in term of
another object so compiler know that it is
Copy Constructor
Now the T replaces as
<double> Instantiation
class Complex<double> {
double real, imag;
public:
Complex( double r, double im ) :
real(r), imag(im) {}
template <typename U>
Complex(const Complex<U>& c) :
real( c.real ), imag( c.imag ) {}
…
};
GooD Complier
Only the Required instantiation are done by Compiler not all
…….
class Complex<float> {
float real, imag;
public:
Complex( float r, float im ) :
real(r), imag(im) {}
// No Copy Constructor code is generated as there is no
need for it
…
};
Class Specialization:
Like Function Template a class may also not
handle all the types successfully so we use
Class Specialization
Syntax
template< >
Class Specialization
template< >
Class Vector< char*>{
Private:
Int size;
Char**ptr;// array to pointers of Character
Public;
Vector<char*>(int=10);
Memory Leak
Here in code we can dynamically allocate the
Memory of Vector so in desructor is called but
we know the size of Vector is 10 on Every
element of Vector the Pointer is pointing so
first we can dsetroy this pointer and then the
Vector is Destroy otherwise Memory Leak for
this purpose we can Deallocte in this Manner
Destructor
template<>
Vector<char*>::~Vector(){
For(int i=0;i<size ; i++)
Delete[]ptr[i];
Delete[]ptr;
} // NULL POINTER WE USE NO EFFECT
So fisrt delete the Memory of Each Element
and then Vector
Non Type Parameter
Template<class T,class U,Int I>
Here int I is non type Parameter
They May have Default value
Template<class T,class U,int I=5>
They are Treated as Constant and commonly
used in Static Memory Allocation
Default Non Type Parameter
We can set default values for this non type
parameter as we do for parameter passed in
ordinary function
template<class T ,int size=10>
Default Parameter
Sytax
template<class T=int>
Class name{
}
name< >v;
Partial Specialization
Partial Specialization of a template provide
more information about the type of Template
argument than that of template
Syntax
Vector<T*> or
Template<class T,class U,int> or
Template<class T ,float,int>
Continue
Similar to Class Template Function Template
may Also be partial specialized
Syntax
Template<class T,class U,class V>
Void func(T,U,V);
Complete Specialization
Syntax
Template<class T>
Complete
Class vector{};
Template<>
Class Vector <char*>{};
OR
Template<int,float,int>
RESOLUTION ORDER in Classes
Sequence in which a compiler searches for
required Template Specialization
First Of all Look For Complete Specilization
Then if Com S… not found than Search for
Partial Specialization
In the End it will Search for General Template
FUNCTION R…O…
Ordinary Function
Complete Specialization
Partial Specialization
Generic Template
Template & Inheritance
A Class Template can be derived from a
Template Class
A class Template can be drived from Non
Template
A Template Class can be drived from class
Template
A non template class can be drived from a
class template
Derivation
Sytax
Same Type in both
Template<class T>
Declaration So
they can be Inherited
Class A{};
Template<class T>
Class B : public A<T>
So a Class Template may Inherit the another
class Template
Inheritance continue…..
A partial specialization may inherit from class
template
Template<class T>
Class B<T*> : public A<T>
Same Type in both
Declaration So
they can be Inherited
Inheritance continue….
Complete Specialization or Ordinary class
cannot inherited from class Template
Template< >
Class B<Char*>:public A<T>
Different Type in both
Declaration So
{};
they cant be Inherited
T is Undefined
Class B: publicA<T>
TEMPLATE & FRIENDS
Rule 1:
Acc to Rule 1 when an ordinary Function or
Class is Declared as Friend of a class template
Then it become a friend of each instantiation
of that Template class
Rule 1:
…Example…..
class A {
…
};
template< class T >
class B {
int data;
friend A; // declaring A as friend of B
…
};
class A {
void method() {
B< int > ib;
B< char > cb
ib.data = 5; // OK: Accessing private member ‘data’ for class B instantiation ib
cb.data = 6; // OK: Accessing private member ‘data’ for class B instantiation cb
}
};
Rule ::::2
when a friend function template or friend class
template is instantiated with the type
parameters of class template granting
friendship then its instantiation for a specific
type is a friend of that class template
instantiation for that particular type only.
RULE 3
When a friend function / class template takes
different ‘type parameters’ from the class
template granting friendship, then its each
instantiation is a friend of each instantiation of
the class template granting friendship.
Basically here we are removing restriction
imposed by Rule 2, due to the use of same type
parameter in class B while declaring function
doSomething and class A as its friends as
shown below,
Pros/cons of Templates
Advantages:
Templates provide
Reusability
Writability
Disadvantages
Can consume memory if used without care.
Templates may affect reliability of a program
PAPERS
A class template may inherit from another class template.
► True (Page 288)
► False
Considering the resolution order in which Considering the resolution order
in which compiler search for functions in a program; the first priority is
given to; the first priority is given to,
► general template
► partial specialization
► complete specialization
► ordinary function (Page 290)
PAPERS
Describe the way to declare a template function as
a friend of any class. 2marks Answer:- (Page 295)
template< class T >
class B
{
int data; friend void doSomething( T ); // granting
friendship to template doSomething in // class B
friend A< T >; // granting friendship to class A in
class B
};
PAPERS
How can we set the default values for non type
parameters? Answer:- (Page 286)
We can set default value for this non type parameters,
as we do for parameters passed in ordinary functions,
template< class T, int SIZE = 10 >
class Array
{ private: T ptr[SIZE]; public: void doSomething();
…}
Cursors
The cursor is pointer that is used outside the
container the following Method help cursor to
Traverse the element
T* first() // pointing to first Element
T* beyond()// last to next
T* next( T* )// current pointer pointing
Cursor
Cursor is used for
contigous sequences
A
B
C
cursor
Cursor is not used with non contiguous because when we apply find
method on container our find Method Increment operator Fails as element
are not placed at next position
ITERATORS
Iterator is an Object that traverse a Container
Iterator are for Container as pointer are for
ordinary Array
For Going to one Element to Other We use
Iterators
Generic Iterator
A generic iterator Works with any kind of
Conatiner to do so a Generic iterator requires
its Container to Provide Three Operation
T*first() // Pointing to First Element of
Container
T*beyond() //one Next to Last
T*next(T*) //gives Next element pointer
Generic Iterator Operation
Operator * // Dereferance to access the
Element
Operator ++ // For Moving To Next Element
of Container we Need Increment
Generic ITerator
Example
Template<class CT ,class ET>
Class Iterator
{
CT* container; // Pointing container
ET* index; // For Accessing Element
……………………
Generic ITerator
Example
Public;
Iterator (CT*c,bool pointAtfirst=true);
Iterator(iterator<CT,ET>&it);// Copy
Constructor
Iterator&operator++();// increment;
ET&operator*();
Bool operator!=(iterator<CT,ET>&it);
};
Conclusion
Iterator Allow the to change the Startegy
without changing the Aggregate object
Iterator is Nothing but a Glorified pointer that
has Encoded into class or pointer iterator is
pointer to a container
Iterator was best design for generic algorithm
Iterator was similar to an ordinary object
Iteratoer Stands to an container and pointer for
array.
PAPERS
Describe three properties necessary a container to
implement generic algorithms. Answer:- (Page
301)
We claimed that this algorithm is generic, because it
works for any aggregate object (container) that
defines following three operations
a. Increment operator (++)
b. Dereferencing operator (*)
c. Inequality operator (!=)
STL
C++ programmer commonly use many Data
Structure and Algorithms
So C++ Standard Committee Added STL to
C++ Standard Libraray
STL Data Structure and ALgoritm are
Designed to operate Effienctly
STL HIERCHY
STL
Containers
Iterators
Algorithms
Three Types of Container
Container
Sequence
Associative
Container Adapter
Three Types of Sequence Container
Sequence Container
Vector
Deque
List
Four Types of Associative
Associative Container
Set
MultiSet
Map
Multimap
Three Types of Container Adapter
Container Adapter
Stack
LIFO
Queue
FIFo
Priorty Queue
Iterator In STL
Five Types
ITERATOR
Input Iterator
OutPUT ITERATOR
Forward Iterator
Bidirectional Iterator
Random Access Iterator
STL
Advantages
Reuse Saves development time and Cost
Onces Tested Component can be used Several
Times
STL
Three Key Components
Container(any data Structure )
Iterator
Algorithm
STL CONTAINER
Container is an object that Contain Collection
of Data Element
STL THREE CONTAINERS
STL Provides Three Containers
Sequence
Associative
Container Adapter
Sequence Container
A sequence Organize a finite Set of Object ,all
of the Same Type, into a Strictly Linear
Arrangement (ordinary Array)
For Example A iron Chain
Three Types of Sequence Container
Vector:
Rapid Inseration and Deletion at Back End
Random Access to Element
Deque: double Ended Queue
Rapid Inseration and Deletion at Front or Back
Random Access to Element
LISTDoubly Link List:
Rapid Inseration and Deletion at any Where
VECTOR EXAMPLE
#include<Vector>
Intmain()
{
Std::vector<int>iv;// Declaration
………..push_back
No pre Define Size It Automatically Grow
Deque Example
#include<deque>
Intmain()
{
Std::deque<int>dq;
dq.push_front(3);
//
back(5);
……..
LIST Example
#include<List>
Intmain()
{
Std::list<int>iv;
Push_back;;;;;
Associative Container
An Associative Container provides Fast
Retrieval of Data based on Keys
Associate a Key with A value
Key is easily Searchable
Key and Element Are Distinct two types
Four Types of Associative Container
Set : No Duplication For E.g Set of Integer
Multi Set: Duplication Allow
Map: No Duplicate Key
Multimap: Duplicate Key Allows
D/F B/w Set and Map?
In Set Element and Key are Same things
In Map Element And Key are two Different
Things
STL SET EXAMPLE
#include<Set>
Int main()
{
Std::Set<char>cs;
Cout<<”Size before inseration”<<cs.size
Cs.insert(“a”)
Cs.insert(“a”)
Cs.insert(“b”) ///// Size is 2 because No duplication
Multi SET Example
#include<Set>
Int main()
{
Std::multiSet<char>cs;
Cout<<”Size before inseration”<<cs.size
Cs.insert(“a”)
Cs.insert(“a”)
Cs.insert(“b”) ///// Size is because allow duplication
Map Example
Key
#include<map>
Int main()
Element Type
Typedef Std::map<int,char>
MyMap;
MyMap m;
m.insert(My Map::value_type(1,a);
First Class Container
Sequence and Associative Container are
Collectively reffered to as the First Class
Container
Underline DataStructure is First Class On
Which Other are Build on it
Container Adapter
A container Adapter is a Constrained version
of Some Forst_class container
Three Type of Container Adapter
Stack >>>>LIFO can Adapt Vector ,Deque
Queue>>>FIFO can Adapt Deque or list
Priority Queue>>>Return Element of Highest
Priorty ,can Adapt vector of Deque
Common Function For All
Container
Default Constructor
Copy Constructor
Destructor
Empty()// Return If No Element
Max_size() // Return Maximum Num of
Element
Size()//return Current number of Element
Common Function For All
Container
Operator=()
//
<=()
//
>()
>=()
==()
!=()
Swap() swap the Element of two Container
Common Function For All
Container
Begin() : return an iterator object that refers to
the first element of the container
End() : return an iterator object that refers to
the next position beyound the last element of
the container
R begin(); return an iterator object that refers
to the last element of the container
R end(); return an iterator object that refers to
the position before the first element
Common Function For All
Container
Erase(iterator); removes an element pointed to
by the iterator
Erase(iterator,iterator): removes the range of
element specified by the first and the second
iterator parameters
Clear(); erases all element from the container
Clear(); erases all element from the container
Container Requirements
Each Container require Element type to
provide a minimum set of functionality
E.g
When an element is inserted into a container a
copy of the element is made
Copy Constructor
Assignemnt Operator
Container Requirements
Associative Container and Many Algorithm
compare Element
Operator ==
Operator <
STL ITERATOR
Iterator are type difines by STL
Iterator are for container Like Pointer are for
ordinary Data Structure
STL iterator provides pointer operation such as
* and ++
STL ITERATOR CATEGORIES
There are Five Catgories
Input iterator
Output Iterator
Forward iterator
Bi directional Iterator
Random Access Iterators
Input Iterators
Can only read an element can only move on
forward direction one element at a time
Support only one pass Al;gorithm
Output Iterators
Can only write an element can only move in
forward direction one element at a time
Support only one pass Algorithm
Forward Iterators
Combine the capabilities of both input and
output iterator in Addition they can book mark
a position in the container
Bi direction Iterators
Provide all the capabilities of forward iterator
In addition they can move in backward
direction
As a result they support multi pass algorithm
Random Access iterators
Provide all Capabilities of bidirectional iterator
In Addition they can Directly access any
element of Container
CONTAINER & ITERATOR
TYPES
Sequence Container :
Vector >>>>RA
Deque >>>RA
List>>RA
ASSOCIATIVE CONTAINER
Set>>>>>>bi directional
Multiset>>>>BD
Map>>>>>>BD
Multimap>>>>BD
CONTAINER & ITERATOR
TYPES
Adapted Container
Stack (none)
Queue (none)
Priority(none)
ALL ITERATOR OPERATION
++p
P++;
Input ITERAtor:
*P
P1=P2
P1!=P2
P==P2
ALL ITERATOR OPERATION
Output Iterator:
*P
P1=P2
Forward Iterator:
Combine op of both input and Output
Bidirection :
--p
P--
ALL ITERATOR OPERATION
Random Access:
Beside the Operation of Bidirectional iterator
They can support
P+I // result is an iterator pointer
P-I // result is an iterator
P+=I
p1<=p2
P-=I
p1>=p2
P[i]
P1<p2
Algorithm
STL Include more than 70 Standard
Algorithms these algorithm may use Iterator
To manipulate container
STL algoritm also Work for ordinary pointer
and Data Type An Algorithm Work with a
Particular container only if that Container
Support a particular Iterator categories
Algorithm
For E,g: a multipass Algorithm reqiuire bi
directional iterator
Examples
MULTATING SEQUENCES
Copy,copy backward,Fill,Fill_n
,remove,replace,sort,swap
Non MULTATATING SEQUENCES:
Adjacent_find,count,count_if,equal,max_elem
ent ,min_element,Search
Exception Handling
Techniques For Error Handling
Abnormal Termination
GraceFull Termination
Return the Illegal Termination
Return Error Code From A function
Eception Handling
Abnormal Termination
No ERROR Detection Compiler itself Close
the Program .or We say Abnormal termination
of Program
GRACE FULL TERMINATION
Program Can be design in a such away that
instead of abnormal termination that can cause
of wastage of resources ,program perform
clean up task,mean we add check for expected
error
You Detect the Error and Inform to user that
I cant Do and Application is Terminated by
programmer
Exception Handling
Summary!!!!!
Most of the Topic are Skipped But Due to
Lack of Time But Almost The important part
is Cover!!! The Very Famous Quotation
Practice make The Perfect
Contact US
For Development of Software in
ASP. Net/Oracle/ C# other Web Designing
IT Solution Consultancy Company …..
THAT ALL!!!!
THANKS!!!!!!!
Your feed Back is Required & Prays
Wish You Best of Luck!!!!!
Admin!!
SHERY.KHAN…………..
[email protected]
www.sherykhan.jimdo.com
+923345042123
+923155042123 // IT CONSULTANCY