Documente Academic
Documente Profesional
Documente Cultură
INHERITANCE
>>>INTRODUCTION
A derived class extends its features by inheriting the properties of another class
(base class) and adding features of its own.
The derivation of a derived class specifies its relationship with the base class, in
addition to its own features.
Syntax
Class derivedclass_name:[visibility mode] baseclass_name
{
/*Members of the derived class, They can also access the members of the base class*/
}
When a class is derived from some other class, the data members of that class
are made available to the derived class. But, which data member is available
>>PUBLIC DERIVATION
The base class is derived with public visibility mode. The syntax of the public
derivation is as follows.
Syntax
Class base // Base class
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 1
Public
members of
the base class
Protected
members of the
base class
Becom
es
Becom
es
Public
members of
Protected
members of the
Derived class
Private
members of the
base class
// Base class
{
private:
int a;
public:
int b;
Prepared by A.V. KALPANA, Asst. ProfessorPage 2
Cannot be
derived
{
private:
int x;
public:
int y;
void setB()
{
x=value;
}
void main()
{
clrscr();
B obj;
obj.a=10; //Error
obj.x=10;//Error
obj.b=10;
obj.y=10;
obj.setA(20);
obj.setB(30);
getch(); }
SINGLE INHERITANCE WITH PRIVATE DERIVATION
Prepared by A.V. KALPANA, Asst. ProfessorPage 3
Public
members of
the base class
Protected
members of the
base class
Private
members of the
base class
Becom
Cannot be
Privatemember
es
derived
s of the Derived
class the visibility mode in the derived class is changed to
For the same program,
private. In this case, the public and protected members of the base class become
the private members of the derived class, so the inherited members(base class)
Prepared by A.V. KALPANA, Asst. ProfessorPage 4
// Base class
{
protected:
int a;
public:
int b;
void setA(int value)
{
a = value;
}
};
class B : public A
// Derived class
{
private:
int x;
public:
int y;
void setB()
{
x=value;
Public
members of
the base class
Protected
members of the
base class
Private
members of the
base class
Becom
es
Cannot be
Protectedmemb
derived
ers of the
For the same
program,class
the visibility mode in the derived class is changed to
Derived
protected. In this case, the public and protected members of the base class
become the protected members of the derived class, so the inherited
members(base class) can be used only inside the derived class & cannot be
accessed in main(). The protectedly derived class is can be further inherited.
EXAMPLE
#include<iostream.h>
#include<conio.h>
class A
// Base class
{
private:
int a;
public:
int b;
void setA(int value)
{
a = value;
}
Prepared by A.V. KALPANA, Asst. ProfessorPage 7
class B : public A
// Derived class
{
private:
int x;
public:
int y;
void setB()
{
x=value;
}
void main()
{
clrscr();
B obj;
obj.a=10; //Error
obj.x=10;//Error
obj.b=10;//Error
obj.y=10;//Error
obj.setA(20);//Error
obj.setB(30);
getch();
}
Note: The only difference between the private and protected derivation is that,
With private derivation, the inherited base class members are private to the
base class and cannot be further inherited.
With protected derivation, the inherited base class members are protected to
the
and isAsst.
available
for further8inheritance
Prepared
bybase
A.V. class
KALPANA,
ProfessorPage
Inheritance is the process by which objects of one class acquire the properties of
the objects of another class. This supports the concept of hierarchical
classification.
Inheritance is the object-oriented feature that supports reusability.
Base class
Derived class
Base class:
It is the class whose members(variables + functions) are inherited by another class.
Derived class:
It is the class that inherits the members(variables + functions) from the base class.
It contains the inherited members as well as its own members.
ADVANTAGES:
1. The concept of inheritance allows the code to be reused as many times as
needed.
2. Saves the time and effort in program development.
TYPES OF INHERITANCE
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multipath Inheritance or Virtual base class or Diamond Inheritance
>>SINGLE INHERITANCE
Deriving a class from only one base class is called as single inheritance.
Prepared by A.V. KALPANA, Asst. ProfessorPage 9
Example:
#include<iostream.h>
#include<conio.h>
class Person
//Base class
{
char *name;
char sex;
int age;
public:
void read()
{
cout<<Name:;
cin>>name;
cout<<Sex:;
cin>>sex;
Prepared by A.V. KALPANA, Asst. ProfessorPage 10
Syntax:
//derived class
{
private:
int rollno;
char *branch;
public:
void read()
{
Person::read();
cout<<Roll No:;
cin>>rollno;
cout<<Branch:;
cin>>branch;
}
void display()
{
Person::display();
Prepared by A.V. KALPANA, Asst. ProfessorPage 11
>>MULTIPLE INHERITANCE
Deriving a class from two or more base classes is called as multiple inheritance.
Base classes
Derived class
Multiple inheritance contains more than one derived class and a single base class.
Syntax:
};
class Derived: public baseclass1, public baseclass2
{
};
Example:
#include<iostream.h>
#include<conio.h>
class InternalExam
//Base class 1
{
protected:
int sub1, sub2;
public:
void read()
{
cout<<Enter the internal marks scored in Subject1:<<
cin>>sub2
cout<<Enter the internal marks scored in Subject2:<<
cin>>sub2;
}
void display()
{
cout<<Internal marks scored in Subject1:<<sub1<<endl;
Prepared by A.V. KALPANA, Asst. ProfessorPage 13
//Base class 1
{
protected:
int sub1, sub2;
public:
void read()
{
cout<<Enter the external marks scored in Subject1:<<
cin>>sub1;
cout<<Enter the external marks scored in Subject2:<<
cin>>sub2;
}
void display()
{
cout<<External marks scored in Subject1:<<sub1<<endl;
cout<<External marks scored in Subject2:<<sub12<<endl;
};
class Result: public InternalExam, public External Exam
{
private:
int sub1total, sub2total;
public:
void read()
{
InternalExam::read();
Prepared by A.V. KALPANA, Asst. ProfessorPage 14
OUTPUT:
InternalExam::display();
ExternalExam::display();
Subject2 Marks: 97
clrscr();
Result r;
r.read();
r.total();
r.display();
getch();
}
Derived class
Deriving a class from another derived class is stated as multilevel inheritance. The
following program illustrates the multilevel inheritance
Syntax:
class Baseclass
{.};
class Derived-classname1: public Baseclass
{..};
class Derived-classname2: public Derived-classname1
{
.
};
EXAMPLE
#include <iostream.h>
#include<conio.h>
class Person
//Base class
{
char *name;
char sex;
int age;
public:
Prepared by A.V. KALPANA, Asst. ProfessorPage 16
Name:RAJ
cin>>sex;
Sex:M
cout<<Age:;
cin>>age;
}
void display()
{
cout<<Name:<<name<<endl;
cout<<Sex:<<sex<<endl;
Age:20
Roll No:1234
Branch:CSE
Enter the marks scored in Subject1:85
Enter the marks scored in Subject2:90
Name:RAJ
cout<<Age:<<age<<endl;
Sex:M
Age:20
};
Roll No:1234
//Intermediate
derived class
Branch:CSE
Subject1 Marks:85
private:
Subject2 Marks:90
int rollno;
Total Marks:175
char *branch;
public:
void read()
{
Person::read();
cout<<Roll No:;
cin>>rollno;
Prepared by A.V. KALPANA, Asst. ProfessorPage 17
>>HYBRID INHERITANCE
Derivation of a class involving more than one form of inheritance is called as
hybrid inheritance.
A
B
D
This is the combination of three types of inheritance: hierarchical, multiple and
multi-level inheritance. Combination of more than one form of inheritance is
called as the hybrid inheritance.
};
class Derived-class-name2: visibility-mode Derived class-name1, visibility-mode
Base-class-name2
{
};
EXAMPLE
The given program is the combination of multilevel and multiple inheritance
#include <iostream.h>
#include<conio.h>
class Person
//Base class
{
char *name;
char sex;
int age;
public:
void read()
{
cout<<Name:;
cin>>name;
Prepared by A.V. KALPANA, Asst. ProfessorPage 20
OUTPUT:
Name: RAM
void display()
Sex: M
Age: 20
cout<<Name:<<name<<endl;
cout<<Sex:<<sex<<endl;
cout<<Age:<<age<<endl;
Game Score: 85
};
class Student : public person
Sex: M
private:
Age: 20
int rollno;
char *branch;
Name: RAM
public:
Subject 1 Marks: 78
void read()
Sports credit: 85
Person::read();
cout<<Roll No:;
cin>>rollno;
cout<<Branch:;
cin>>branch;
}
void display()
Prepared by A.V. KALPANA, Asst. ProfessorPage 21
>>HIERARCHICAL INHERITANCE
Deriving two or more classes from a single base class is called as Hierarchical
inheritance.
Base classes
Derived classes
This contains one base class and more than one derived class.
class Base-class-name
{
};
class Derived-class-name1: visibility-mode Base-class-name
{
..
};
class Derived-class-nameN: visibility-mode Base-class-name
{
.
Prepared by A.V. KALPANA, Asst. ProfessorPage 24
EXAMPLE
#include <iostream.h>
#include<conio.h>
class Person
//Base class
{
char *name;
char sex;
int age;
public:
void read()
OUTPUT:
cout<<Name:;
Name:Ajay
cin>>name;
Sex:M
Age:21
cout<<Sex:;
cin>>sex;
Name:Ajay
cout<<Age:;
Sex:M
cin>>age;
}
Age:21
Enter the Employee's details:
Name:Vijay
void display()
Sex:M
Age:22
cout<<Name:<<name<<endl;
cout<<Sex:<<sex<<endl;
cout<<Age:<<age<<endl;
Name:Vijay
Sex:M
Age:22
}
Prepared by A.V. KALPANA, Asst. ProfessorPage 25
{
public:
void read()
{
cout<<Enter the Students details:<<endl;
Person::read();
}
void display()
{
cout<<Print the Students details:<<endl;
Person::display();
}
};
class Employee : public Person{
public:
void read()
{
cout<<Enter the Employees details:<<endl;
Person::read();
}
void display()
{
cout<<Print the Employees details:<<endl;
Person::display();
}
Prepared by A.V. KALPANA, Asst. ProfessorPage 26
A
B
Multipath
Inheritance
The syntax for the above hierarchy of inheritance
is
Class A
{ };
Class B:public A
{ };
Class C:public A
D
{ };
Class D:public B,public C
{ };
In this hierarchy, the class D has two direct base classes B and C, which has the
compilation.
The duplication of the inherited members due to these multiple paths can be
avoided by making the common base class(class A) as the virtual base class while
declaring the direct or intermediate base class. The syntax to achieve virtual base
class concept is given as follows:
Class A
{ };
Class B: virtual public A
{ };
Class C: public virtual A
The keywords virtual and
{ };
public may be used in either
Class D: public B, public C
{
/*Only one copy of A will be inherited and the single copy will be shared by class
B & class C, since the common base class is made virtual*/
};
When a class is made a virtual base class, only one copy of that class is
inherited and shared by the derived classes, regardless of the number of
inheritance paths exists between Virtual base class and the derived class.
EXAMPLE
#include<iostream.h>
#include<conio.h>
class A
{
public:
int i;
};
OUTPUT:
Value of i is : 10
Value of j is : 20
Value of k is :30
Sum is : 60
void main()
{
clrscr();
D ob;
ob.i = 10; //Does not cause error, since only one copy of i is inherited by D
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout <<"Value of i is : "<< ob.i<<"\n";
cout <<"Value of j is : "<< ob.j<<"\n";
cout <<"Value of k is :"<< ob.k<<"\n";
cout <<"Sum is : "<< ob.sum <<"\n";
getch();
}
=====================================================================
RUN TIME POLYMORPHISM
Polymorphism is one of the OOPs feature which means, one name, multiple
forms.
The classification of polymorphism can be given as follows:
The compile time polymorphism can also be called as static binding or early
binding. This is implemented using the overloaded functions and operators.
The corresponding member function is selected by matching the arguments, type
of the argument and number of arguments.
This information is known to the compiler at the time of compiling the program.
So, this is called as Compile Time polymorphism.
The run-time polymorphism can also be called as dynamic binding or late binding.
This is implemented using Virtual functions.
When the same function with the same prototype is declared both in the base
class and derived class, it is called as function overriding.
The appropriate member function could be selected at the time of running the
program. So, this is called as Runtime polymorphism.
>>VIRTUAL FUNCTIONS
In virtual functions, the pointer to the base class is used to refer to all the
derived class objects.
The class that contains a virtual function is called as the polymorphic class.
Eventhough, a base pointer is made to contain the address of the derived class
object; it always executes the function in the base class.
Prepared by A.V. KALPANA, Asst. ProfessorPage 30
OUTPUT:
I am a Shape
Shape *ptrs, s;
Circle c;
ptrs=&s;
ptrs draw();
Prepared by A.V. KALPANA, Asst. ProfessorPage 31
I am a Circle
Without mentioning the base class function as virtual, the output will be
I am a Shape
I am a Shape
Instead of
I am a Shape
I am a Circle
This is because the base classs function would be repeatedly called, as the base pointer
executes the function in the base class.
If the function in the base class is designated as virtual , then the derived classs
function would be called. If it is not virtual, the base classs function would be
called.
The pure virtual function (or abstract function) is a virtual function which does not
Syntax:
Virtual return_type function_name()=0;
class A //Abstract class
{
public:
virtual void func() = 0; // pure virtual function
};
Class A
Class C
{
B b;
C c;
A *x = &b;
A *y = &c;
x func();
yfunc();
}
>>RULES FOR PURE VIRTUAL FUNCTION
Syntax:
Virtual return_type function_name()=0;
class A //Abstract class
{
public:
virtual void func() = 0; // pure virtual function
};
class B: public A
{
public:
void func() // overriding the pure virtual function & implementing it
{
cout << "Class B";
}
};
OUTPUT:
class C: public B
{
public:
Prepared by A.V. KALPANA, Asst. ProfessorPage 34
Class A
Class C
Exception Handling
The process of catching and handling exceptions is known as exception handling.
The exception handling mechanism suggests a separate error handling code that performs
the following tasks:
1. Find the problem(Hit the exception)
2. Inform that the error has occurred(Throw the exception)
3. Receive the error information(Catch the exception)
4. Take corrective actions(Handle the exception)
An Exception is an object. It is sent from the part of the program where an error occurs
to that part the program which is going to control the error.
There are two types of exceptions,
Synchronous Exceptions,
Asynchronous Exceptions.
try: try block is identified by a block of statement. The try block is indicated by try
keyword followed by block of statements enclosed in braces. The main purpose of this
block is to generate an exception.
throw: when an exception has been detected in the try block it is thrown by throw
keyword in the try block.
catch: catch block identifies catching an exception. Catch block catches the exception
thrown by the throw statement in the try block. A catch block begins with keyword catch
with parenthesis which says the type of exception to which it has to act.
}
The type indicates the type of exception that catch block handles. The parameter arg is
optional parameter name.
The catch statement catches an exception whose type matches with the type of catch
argument. When it is caught, the code in the catch block is executed.
If the parameter in the catch statement is named, then the parameter can be used in the
exception-handling code. After executing the handler, the control goes to the statement
immediately following the catch block.
Due to mismatch if an exception is not caught, abnormal program termination will occur.
***Note: The catch block is simply skipped if the catch statement does not catch an
exception.
Throw Mechanism
OUTPUT:
RUN 1
cin>>b;
cin>>c;
try
{
if((a-b)!=0)
{
d=c/(a-b);
Enter
Prepared by A.V. KALPANA, Asst. ProfessorPage
39the value of c:--40
Answer is infinite because a-b is: 0
type function(arg-list)
//function with exception
{
throw(object);
//throws exception
..
}
.
.
tryFunction invoked by try block throwing exception
Fig.
{
Syntax:
..
..
//invoke function here
..
}
catch(type arg)
//Catches exception
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 40
.
//Handles exception here
.
}
RETHROWING AN EXCEPTION
A handler may decide to re-throw an exception caught without processing it. In such
situations, we may simply invoke throw without any arguments as shown below:
throw;
This causes the current exception to be thrown to the next enclosing try/catch sequence
and is caught by a catch statement listed after that enclosing try block. The following
program demonstrates how an exception is re-thrown and caught.
Example: Program to illustrate re-throwing of exception
#include<iostream.h>
void divide(int x, double y)
OUTPUT:
Inside main
{
cout<<"Inside function"<<endl;
Inside function
Division=5.25
try
End of function
Inside function
Caught double inside function
OUTPUT:
Testing multiple catches
Catch a integer and that integer is: 10
Catch a character and that character is: x
If the user wants to deny a function from throwing exception then the user can declare
data type list as void.
throw (); // void or vacant list
Program to restrict a function to throw only specified type of exceptions:
void check (int k) throw (int, double)
{
if (k == 1) throw k;
else if (k ==2) throw k;
else if (k ==-2) throw 1.0;
cout<< End of Function Check();
}
void main ()
{
try
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 45
OUTPUT:
K ==1
Caught a Char Exception
End of main
OUTPUT:
An uncaught exception
Abnormal program execution
OUTPUT:
Throwing exception
is invoked
Prepared by A.V. KALPANA, Asst. ProfessorPageMyTerminate
47
OUTPUT:
RUN 1
if(num>0)
cout<<positive number<<endl;
else
if(num<0)
Positive number
End of main
cout<<Negative number<<endl;
RUN 2
else
throw zero();
Negative number
}
void main()
{
End of main
RUN 3
OUTPUT:
RUN 1
if(num>0)
cout<<positive number<<endl;
else
Positive number
End of main
if(num<0)
RUN 2
cout<<Negative number<<endl;
else
Negative number
throw zero();
}
void MyUnexpected()
End of main
RUN 3
Templates enable to define generic classes and functions and thus support generic
programming.
Generic programming is an approach where generic types are used as
parameters, so that they can work for a variety of suitable data types.
A template can be used to create a family of classes or functions.
algorithms
are
written
in
terms
of to-be-specified-
later types that are then instantiated when needed for specific
types
provided
as
parameters.
This
approach,
pioneered
and Visual
Basic
language
that
supports
both
parameterized
types
"generic"
for
related
but
somewhat
and parameterized
different
types in
the
authors
of Design
Patterns note
that
this
technique,
programming
certain statically
typed
refers
to
programming
features
of
languages that
are
qualified
by
type
variable.
Since
code
iterators,
and
algorithms.
Examples
of
containers are vectors, queues, sets, maps, and lists and hash
tables and functions such as a particular sorting algorithm for
objects specified in terms more general than a concrete type.
Generic
programming
pioneer Alexander
Stepanov wrote:
class add
{
T a,b,c;
public:
void getdata(T x, T y)
{
a=x;
b=y;
}
void display()
{
c=a+b;
cout<<c<<endl;
}
};
void main()
{
clrscr();
add <int> obj1;
cout<<"Sum of integers:";
obj1.getdata(5,4);
obj1.display();
add <float> obj2;
cout<<"Sum of float type:";
obj2.getdata(1.5,3.1);
OUTPUT:
Sum of integers: 9
The statement, add <int> obj1; Invoke the class template with datatype int. i.e
all the template type variables and arguments(T) are replaced with integer type.
The statement, add <float> obj2; Invoke the class template with datatype float.
i.e all the template type variables and arguments(T) are replaced with float type
More than one generic datatype can be used in a class template. They are
declared as a comma-seperated list within the template specification
Syntax:
template< class T1, class T2,>
class class_name
{
/* Class member specification with anonymous types T1 & T2 wherever appropriate*/
}
Syntax to invoke the class
Classname <datatype1, datatype2,> objectname;
EXAMPLE
#include<iostream.h>
#include<conio.h>
template<class T1, class T2>
class test
{
T1 a;
T2 b;
public:
test(T1 x, T2 y)
OUTPUT:
test<int,char> obj2(100,'K');
obj1.show();
obj2.show();
getch();
}
In this program,
The statement, test <int, float> obj1(123,1.23); Invokes the class template by
replacing the first template type (T1) by int type and the second template type
***FUNCTION TEMPLATE
Definition:
Function templates can be used to create a family of functions with different
argument types.
Syntax:
template<class T>
Prepared by A.V. KALPANA, Asst. ProfessorPage 55
t=x;
x=y;
y=t;
}
void main()
{
clrscr();
char ch1,ch2;
cout<<"Enter the characters to swap"<<endl;
cin>>ch1>>ch2;
swap(ch1,ch2);
OUTPUT:
cout<<"After swapping"<<endl;
cout<<ch1<<" "<<ch2<<endl;
int a,b;
cout<<"Enter the integers to swap"<<endl;
cin>>a>>b;
swap(a,b);
cout<<"After swapping"<<endl;
cout<<a<<" "<<b<<endl;
getch();
Prepared by A.V. KALPANA, Asst. ProfessorPage 56
EXAMPLE
#include<iostream.h>
#include<conio.h>
template<class T1,class T2> // Template declaration with two arguments.
void display(T1 x, T2 y) //Function definition with template type arguments T1,T2.
{
cout<<x<<" "<<y<<"\n";
}
void main()
{
clrscr();
display(100,"ABC");
display(12.34, 123);
getch();
}
In this program,
Prepared by A.V. KALPANA, Asst. ProfessorPage 57
OUTPUT:
100 ABC
12.34 123
void display()
{
c=a+b;
cout<<c<<endl;
}
Prepared by A.V. KALPANA, Asst. ProfessorPage 58
{
a=x;
b=y;
}
void main()
{
clrscr();
add <int> obj1;
cout<<"Sum of integers:";
obj1.getdata(5,4);
obj1.display();
OUTPUT:
Sum of integers: 9
obj2.display();
getch(); }
In this program,
A template with multiple arguments can also have the non-type arguments, which
means, in addition to the type argument T, the other arguments such as strings,
..
};
This template supplies the size of the array as an argument(non-type). The arguments
must be created when the template class is created.
Eg: array<int, 5> a1;
OUTPUT:
5
{
cout<<Explicit Display:<<x<<\n;
OUTPUT:
void main()
{
clrscr();
display(100);
display(12.34);
display(C);
getch();
}
In this program, the call display (100) invokes the ordinary version of display() and not
the template version.
Prepared by A.V. KALPANA, Asst. ProfessorPage 61
iterators.
STL is different from normal libraries. All other libraries defined need entities as
classes.
The operations required in that class are written as member functions of the class.
But STL has number of non member functions designed to work on multiple classes
of container classes.
A container is an object that actually stores data. It is a way that stored data is
organized in memory, for example an array of elements.
Algorithms are procedures that are applied to containers to process the data, for
example search for an element in an array, or sort an array. Algorithms are
implemented by template functions.
1.Containers
Prepared by A.V. KALPANA, Asst. ProfessorPage 62
STL Containers
Header
Contents
<vector>
An array of T
<list>
A doubly-linked list of T
<deque>
A double-ended queue of T
<queue>
A queue of T
<stack>
A stack of T
<map>
An associative array of T
<set>
A set of T
<bitset>
in
an
unordered
form
inserted.
Element is accessed by index or position of Element is accessed by the value of key
the element.
Contents
<algorithm>
3.Iterators
Iterators are like pointers and can be used to traverse and list out container contents.
They are defined in the following header file.
STL Iterators
Header
Contents
<iterator>
Numeric Library
STL provides several classes and algorithms that are specifically designed for numeric
computations
Numeric Containers and Algorithms
Header
Contents
<complex>
<valarray>
<numerics>
Utilities
The following headers define auxiliary components that are used in STL containers and
algorithms. These include function adaptors, pairs, and class auto_ptr.
General Utilities
Header
Contents
<utility>
<functional>
Function objects
<memory>
Sequence Containers
The sequence containers store the elements in a sequence. Some of them are vector,
deque and list.
Vector
Prepared by A.V. KALPANA, Asst. ProfessorPage 66
v.pop_back();
#include<vector>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
Prepared by A.V. KALPANA, Asst. ProfessorPage 67
OUTPUT:
vector<int> vi;
11
vi.push_back(11);
vi.push_back(12);
vector<int>::iterator intindex;
for(intindex=vi.begin();intindex<vi.end(); intindex++)
12
1234
AAA
4567
BBB
{
cout<<*intindex<<endl;
}
vector<Student>vs;
Student s1(1234, AAA);
Student s2(4567, BBB);
vs.push_back(s1);
vs.push_back(s2);
vector<Student>::iterator StudentIndex;
for(StudentIndex=vs.begin(); StudentIndex!=vs.end();StudentIndex++)
{
cout<<*StudentIndex<<endl;
}
}
List
Prepared by A.V. KALPANA, Asst. ProfessorPage 68
An STL list container is a double linked list, in which each element contains a pointer
to its successor and predecessor.
It supports a bidirectional, linear list and provides and efficient implementation for
deletion and insertion operations.
Unlike a vector, which supports random access, a list can be accessed sequentially
only.
It is possible to add and remove elements from both ends of the list
Lists do not allow random access but are efficient to insert new elements and to sort
and merge lists
#include<list>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
Prepared by A.V. KALPANA, Asst. ProfessorPage 69
OUTPUT:
list<int>::iterator intindex;
11
for(intindex=li.begin();intindex!=li.end();intindex++)
12
1234
AAA
4567
BBB
cout<<*intindex<<endl;
}
list<Student> ls;
Student s1(1234, AAA);
Student s2(4567, BBB);
ls.push_back(s1);
ls.push_back(s2);
list<Student>::iterator StudentIndex;
for(StudentIndex=ls.begin(); StudentIndex!=ls.end();StudentIndex++)
{
cout<<*StudentIndex;
}
}
Generic Algorithm: find() with list
#include<list>
#include<string>
#include<iostream>
class Student
{
int rollno;
Prepared by A.V. KALPANA, Asst. ProfessorPage 70
OUTPUT:
11
12
1234
AAA
1237
MMM
ls.push_back(s2);
1235
BBB
ls.push_back(s3);
1236
CCC
ls.push_back(s1);
list<Student>::iterator StudentIndex;
Student s4(1237, MMM);
StudentIndex=find(ls.begin(), ls.end(), s2);
ls.insert(StudentIndex, s4);
for(StudentIndex=ls.begin(); StudentIndex!=ls.end();StudentIndex++)
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 71
It is a useful container adapted into two other containers namely queue and stack.
Here push_front() is used to insert the elements
Deque is a structure where the insertion takes place at either the end or the begin
position.
The push_front() function adds the element in the beginning so that the data
entered is displayed in the reverse order.
#include<deque>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<endl;
}
};
void main()
Prepared by A.V. KALPANA, Asst. ProfessorPage 72
OUTPUT:
12
11
1236
CCC
ds.push_front(s2);
1235
BBB
ds.push_front(s3);
1234
AAA
ds.push_front(s1);
deque<Student>::iterator StudentIndex;
for(StudentIndex=ds.begin(); StudentIndex!=ds.end();StudentIndex++)
{
cout<<*StudentIndex;
}
}
Sorted Associative Containers
Map
o A map is a sequence of (key,value) pairs where a single value is associated with
each unique key
o Retrieval of values is based on the key and is very fast.
o A map is commonly called as an associative array.
o The key is specified using the subscript operator[ ].
OUTPUT:
Student s1(Mohit);
Lohit
Mohit 1
Rohit
Multimap is a container which can have entry with multiple values for a single key.
The insert function expects a pair of objects to be inserted. Pair is a template
known as second.
Every element, when inserted, is inserted where it is to be inserted in the sorted
order.
#include<map>
#include<string>
#include<iostream>
class Student
{
string name;
public:
Student(){}
Student(string tname)
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 75
OUTPUT:
Lohit
Mohit 1
Rohit
Student s3(Rohit);
m1.insert(pair<Student,int>(s1,1));
m1.insert(pair<Student,int>(s2,2));
m1.insert(pair<Student,int>(s3,3));
for(StudentIndex=m1.begin(); StudentIndex!=m1.end();StudentIndex++)
{
cout<<StudentIndex->first<<\t;
cout<<StudentIndex->second<<endl;
}
}
Set
We can insert all keys and when the key is referenced we can see if the key
#include<set>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<\n;
}
bool operator <(Student tstudent) const
{
return(rollno<tstudent.rollno);
}
};
void main()
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 77
OUTPUT:
1234
Mohit
1235
Lohit
1236
Rohit
OUTPUT:
1234
Mohit
multiset<Student> mss;
1234
Mohit
1235
Lohit
Student s2(1235,Lohit);
1235
Lohit
Student s3(1236,Rohit);
1236
Rohit
1236
Rohit
mss.insert(s1);
mss.insert(s2);
mss.insert(s3);
mss.insert(s1); //inserting the same data second time
mss.insert(s2);
mss.insert(s3);
Set<Student>::iterator Studentindex;
stack.
empty() - used to check whether the stack has any item or not.
top() - to move the stack pointer to the top of the stack.
#include<stack>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<\n;
}
};
void main()
{
Stack<Student> ss;
Student s1(1234, Mohit);
Prepared by A.V. KALPANA, Asst. ProfessorPage 80
OUTPUT:
1236
Rohit
1235
Lohit
1234
Mohit
OUTPUT:
1234
Mohit
Queue<Student> qs;
1235
Lohit
1236
Rohit
Student s2(1235,Lohit);
Student s3(1236,Rohit);
qs.pus(s1);
qs.push(s2);
qs.push(s3);
Student st;
while(!qs.empty())
{
st=qs.front(); // this is the one difference from stack & queue
cout<<st.name<<\t<<st.rollno<<endl;
qs.pop();
}
}
ITERATORS
o Iterators are like pointers and can be used to traverse and list out container
contents.
o They are often used to traverse from one element to another, a process known as
iterating through the container.
There are two model to manage multiple objects. These methods are
o Address mechanism : The pointers to array element represent a model of address
mechanism
o Functional mechanism : The file access using get() and put() use a functional
mechanism