Oops Practical
Oops Practical
SE-COMPUTER ENGINEERING
SEMESTER-III
Name
Roll No.
Date
Signature
Problem Statement:
Implement a class Complex which represents the Complex Number data type. Implement the following
operations:
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overloaded operator+ to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >>to print and read Complex Numbers.
Prerequisites:
Objectives:
To learn the concept of constructor, default constructor, operator overloading using member function
and friend function.
Theory:
Operator Overloading
It is a specific case of polymorphism where different operators have different implementations
depending on their arguments. In C++ the overloading principle applies not only to functions, but to
operators too. That is, of operators can be extended to work not just with built-in types but also classes. A
programmer can provide his or her own operator to a class by overloading the built-in operator to
perform some specific computation when the operator is used on objects of that class.
Arithmetic Operators
Arithmetic Operators are used to do basic arithmetic operations like addition, subtraction, multiplication,
division, and modulus.
The following table list the arithmetic operators used in C++.
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
With C++ feature to overload operators, we can design classes able to perform operations using
standard operators. Here is a list of all the operators that can be overloaded:
Over loadable operators
+ - * / = <> += -= *= /= <<>>
<<= >>= == != <= >= ++ -- % & ^ ! |
~ &= ^= |= && || %= []
5. To overload an operator in order to use it with classes we declare operator functions, which are
regular functions whose names are the operator keyword followed by the operator sign that we
want to overload. The format is:
6. type operator operator-symbol (parameters) {/*...*/ }
7. The operator keyword declares a function specifying what operator-symbol means when
applied to instances of a class. This gives the operator more than one meaning, or "overloads"
it. The compiler distinguishes between the different meanings of an operator by examining the
types of its operands.
Syntax:
return_typeclass_name :: operator op(arg_list)
{
//function body
}
where,
8. Return type is the value returned by the specified operation
9. op is the operator to be overload.
10. op is proceeding by the keyword operator.
11. operator op is the function name
Process of the overloading has 3 steps
1. Create a class that define a data types that is used in the overloading operation
2. Declare the operator function operator op () in the public part of the
class. It may be either a member function or a friend function.
3. Define the operator function to implement the required operation
e.g.
Overloading Binary operators:
A statement like
C = sum (A, B); // functional notation
This functional notation can be replaced by a natural looking expression
C = A+B; // arithmetic notation
by overloading the + operator using an operator+ () function
Algorithm:
Input:
Complex numbers with real and imaginary values for two complex numbers.
Example:
Complex No 1: Real Part : 5
Imaginary part : 4
Complex No 2: Real Part : 5
Imaginary part : 4
Output:
# include<iostream>
using namespace std;
class Complex
{
double real;
double img;
public:
Complex();
friend istream & operator >> (istream &, Complex &);
friend ostream & operator << (ostream &, const Complex &);
Complex operator + (Complex);
Complex operator * (Complex);
};
Complex::Complex()
{
real = 0;
img = 0;
}
istream & operator >> (istream &, Complex & i)
{
cin >> i.real >> i.img;
return cin;
}
ostream & operator << (ostream &, const Complex & d)
{
cout << d.real << " + " << d.img << "i" << endl;
return cout;
}
Complex Complex::operator + (Complex c1)
{
Complex temp;
temp.real = real + c1.real;
temp.img = img + c1.img;
return temp;
}
Complex Complex::operator * (Complex c2)
{
Complex tmp;
tmp.real = real * c2.real - img * c2.img;
tmp.img = real * c2.img + img * c2.real;
return tmp;
}
int main()
{
Complex C1, C2, C3, C4;
int flag = 1;
char b;
while (flag == 1)
{
cout << "Enter Real and Imaginary part of the Complex Number 1 : \n";
cin >> C1; 2+4i;
cout << "Enter Real and Imaginary part of the Complex Number 2 : \n";
cin >> C2; 3+2i;
int f = 1;
while (f == 1)
{
ubuntu@user:~$ ./a.out
Complex Number 1 : 2 + 3i
Complex Number 2 : 3 + 4i
**********MENU**********
3. Exit
Addition : 5 + 7i
Complex Number 1 : 2 + 3i
Complex Number 2 : 3 + 4i
**********MENU**********
3. Exit
Questions:
1. What is operator overloading?
2. What are the rules for overloading the operators?
3. State clearly which operators are overloaded and which operator are not overloaded?
4. State the need for overloading the operators.
5. Explain how the operators are overloaded using the friend function.
6. What is the difference between “overloading” and “overriding”?
7. What is operator function? Describe the syntax?
8. When is Friend function compulsory? Give an example?
Name
Roll No.
Date
Signature
Problem Statement:
Prerequisites:
Objectives:
To learn the concept of constructor, default constructor, copy, destructor, static member functions,
friend class, this pointer, inline code and dynamic memory allocation operators-new and delete.
Theory:
Constructor:
A special method of the class that will be automatically invoked when an instance of the class is
created is called as constructor. Following are the most useful features of constructor.
1) Constructor is used for Initializing the values to the data members of the Class.
2) Constructor is that whose name is same as name of class.
3) Constructor gets Automatically called when an object of class is created.
4) Constructors never have a Return Type even void.
5) Constructor is of Default, Parameterized and Copy Constructors.
The various types of Constructor are as follows: -
Constructors can be classified into 3 types
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor: - Default Constructor is also called as Empty Constructor which has no
arguments and It is Automatically called when we create the object of class but Remember name of
Constructor is same as name of class and Constructor never declared with the help of Return Type.
JCEI’s Jaihind College of Engineering, Kuran 2021-2022
Means we can‟t declare a Constructor with the help of void Return Type., if we never Pass or declare
any Arguments then this called as the Copy Constructors.
2. Parameterized Constructor: - This is another type constructor which has some Arguments and
same name as class name but it uses some Arguments So For this, we have to create object of Class by
passing some Arguments at the time of creating object with the name of class. When we pass some
Arguments to the Constructor then this will automatically pass the Arguments to the Constructor and
the values will retrieve by the Respective Data Members of the Class.
3. Copy Constructor: - This is also another type of Constructor. In this Constructor we pass the object
of class into the Another Object of Same Class. As name Suggests you Copy, means Copy the values
of one Object into another Object of Class .This is used for Copying the values of class object into
another object of class So we call them as Copy Constructor and For Copying the values We have
to pass the name of object whose values we wants to Copying and When we are using or passing an
Object to a Constructor then we must have to use the & Ampersand or Address Operator.
Destructor: As we know that Constructor is that which is used for Assigning Some Values to data
Members and For Assigning Some Values This May also used Some Memory so that to free up the
Memory which is Allocated by Constructor, destructor is used which gets Automatically Called at the
End of Program and we doesn‟t have to Explicitly Call a Destructor and Destructor Can‟t be
Parameterized or a Copy This can be only one Means Default Destructor Which Have no Arguments.
For Declaring a Destructor, we have to use ~tiled Symbol in front of Destructor.
Static members
A class can contain static members, either data or functions.
A static member variable has following properties:
• It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
• Only one copy of that member is created for the entire class and is shared by all the objects of
that class.
• It is the visible only within the class but its lifetime is the entire program.
Static data members of a class are also known as "class variables", because there is only one unique
value for all the objects of that same class. Their content is not different from one object static members
have the same properties as global variables but they enjoy class scope. For that reason, and to avoid
them to be declared several times, we can only include the prototype (its declaration) in the class
declaration but not its definition (its initialization). In order to initialize a static data-member we must
include a formal definition outside the class, in the global scope of this class to another. Because it is a
unique variable value for all the objects of the same class, it can be referred to as a member of any object
of that class or even directly by the class name (of course this is only valid for static members.
• A static function can have access to only other static members (fun or var) declared in the same
class
• A static function can be called using the class name instead of its object name
class name :: fun name ;
Static member functions are considered to have class scope. In contrast to non-static member functions,
these functions have no implicit this argument; therefore, they can use only static data members,
enumerators, or nested types directly. Static member functions can be accessed without using an object
of the corresponding class type.
Output
9
Friend functions:
In principle, private and protected members of a class cannot be accessed from outside the same class
in which they are declared. However, this rule does not affect friends. Friends are functions or classes
declared as such. If we want to declare an external function as friend of a class, thus allowing this
function to have access to the private and protected members of this class, we do it by declaring a
prototype of this external function within the class, and preceding it with the keyword friend.
Properties of friend function:
• It is not in the scope of the class to which it has been declared as friend.
• Since it is not in the scope of the class, it cannot be called using the object of that class
• It can be invoked like a normal function w/o the help of any object.
• It can be declared in private or in the public part of the class.
• Unlike member functions, it cannot access the member names directly and has to use an object
name and dot operator with each member name.
// friend functions
#include <iostream>
using namespace std;
class CRectangle {
int width, height;
public:
void set_values (int, int);
int area () {return (width * height);}
friend CRectangle duplicate (CRectangle);
};
void CRectangle :: set_values (int a, int b)
{ width = a;
height = b;
}
CRectangle duplicate (CRectanglerectparam)
{
CRectanglerectres;
The duplicate function is a friend of CRectangle. From within that function we have been able to access
the members width and height of different objects of type CRectangle, which are private members.
Notice that neither in the declaration of duplicate () nor in its later use in main () have we considered
duplicate a member of class CRectangle.
Friend classes
Just as we have the possibility to define a friend function, we can also define a class as friend of
another one, granting that second class access to the protected and private members of the first one.
// friend class
#include <iostream>
using namespace std;
class CSquare;
class CRectangle
{
int width, height;
public:
int area ()
{return (width * height);}
void convert (CSquare a);
};
class CSquare {
private:
int side;
public:
void set_side (int a)
{side=a;}
friend class CRectangle;
};
void CRectangle::convert (CSquare a) {
width = a.side;
height = a.side;
}
int main () {
CSquaresqr;
CRectanglerect;
sqr.set_side(4);
rect.convert(sqr);
cout<<rect.area();
return 0;
}
Pointers:
A pointer is a derived data type that refers to another data variable by storing the variables memory
address rather than data.
Declaration of pointer variable is in the following form:
Eg. int *ptr;
Data_type * ptr_var;
Pointers to objects:
this pointer:
C++ uses a unique keyword called this to represent an object that invokes a member function. thisis a
pointer that points to the object for which this function was called. This unique pointer is automatically
passed to a member function when it is called.
Important notes on this pointer:
• this pointer stores the address of the class instance, to enable pointer access of the members to
the member functions of the class.
• this pointer is not counted for calculating the size of the object.
• this pointers are not accessible for static member functions.
• this pointers are not modifiable.
Facilities:
Algorithm:
1. Start
Input:
Personnel information such as Name, Date of Birth, Blood group, Height, Weight, Insurance Policy,
number, contact address, telephone number, driving license no.
Output:
#include<string.h>
class Data
string address;
public:
void input_student_data();
void display_student_data();
};
class Student
string Name;
int Roll;
string Class;
char *Div;
string dob;
char *bg;
public:
Student();
~Student();
return count;
};
Data::Data()
Data::~Data()
delete telephone;
delete dl_no;
void Data::input_student_data()
cin.ignore();
getline(cin,address);
cin>>*telephone;
cin>>*dl_no;
void Data::display_student_data()
Student::Student()
Roll = 0;
dob = "dd/mm/yyyy";
bg = new char[5];
Student::~Student()
delete Div;
delete[] bg;
cout<<"Name : ";
cin.ignore();
getline(cin,Name);
cin>>Roll;
cout<<"Class : ";
cin.ignore();
getline(cin,Class);
cout<<"Division : ";
cin>>Div;
cin.ignore();
getline(cin,dob);
stud1->input_student_data();
count++;
cout<<"Name : "<<Name<<endl;
cout<<"Class : "<<Class<<endl;
cout<<"Division : "<<Div<<endl;
stud2->display_student_data();
cout<<" \n";
int Student::count;
int main()
Student *st1[100];
Data *st2[100];
int a;
int s=0;
char ch;
do
cout<<"3.Exit\n";
cin>>a;
case 1 :
do
st1[s]->input_data(st2[s]);
s++;
cin>>ch;
}while(ch=='y' || ch=='Y');
break;
case 2:
cout<<"**************************StudentDatabase****************************"<<endl;
for(int j=0;j<s;j++)
st1[j]->display_data(st2[j]);
break;
case 3:
JCEI’s Jaihind College of Engineering, Kuran 2021-2022
{
exit(0);
default:
}while(ch!=3);
return 0;
ubuntu@user:~$ ./a.out
MENU
1. New Student
2. View Database
MENU
1. New Student
2. View Database
Name : OMKAR
Roll Number : 29
Class : SE COMP
Division : A
Blood Group : B+
Name : ATHARVA
Roll Number : 27
Class : SE COMP
Blood Group : B+
MENU
1. New Student
2. View Database
**************************StudentDatabase****************************
Name : OMKAR
Roll Number : 29
Class : SE COMP
Division : A
Blood Group : B+
Name : ATHARVA
Roll Number : 27
Class : SE COMP
Division : A
Blood Group : B+
Conclusion:
Hence, we have successfully studied concept of constructor, default constructor, copy constructor,
destructor, static member functions, friend class, this pointer, inline code and dynamic memory
allocation operators-new and delete.
Questions:
Name
Roll No.
Date
Signature
Title: Creating a class which uses the concept of inheritance, displays data and data
members and uses the concept of exception handling.
Problem Statement:
Imagine a publishing company which does marketing for book and audio cassette
versions. Create a class publication that stores the title (a string) and price (type float)
of publications. From this class derive two classes: book which adds a page count
(type int) and tape which adds a playing time in minutes (type float). Write a program
that instantiates the book and tape class, allows user to enter data and displays the
data members. If an exception is caught, replace all the data member
values with zero values.
Prerequisites:
Objectives:
Theory:
Inheritance:
Inheritance in Object Oriented Programming can be described as a process of creating new classes from
existing classes. New classes inherit some of the properties and behavior of the existing classes. An
existing class that is "parent" of a new class is called a base class. New class that inherits properties of
the base class is called a derived class. Inheritance is a technique of code reuse. It also provides
possibility to extend existing classes by creating derived classes.
The basic syntax of inheritance is:
Single Inheritance:
In this type of inheritance one derived class inherits from only one base class. It is the most simplest
form of Inheritance.
Syntax:
// Single Inheritance
#include <iostream>
using namespacestd;
class Vehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
Class Car: public Vehicle
{
};
int main()
{
Car obj;
return0;
}
Output:
This is a Vehicle.
In this type of inheritance, a single derived class may inherit from two or more than two base classes.
Syntax:
// Multiple Inheritence
#include <iostream>
using names pace
std;
Class Vehicle
{ public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
Class FourWheeler
{ public:
FourWheeler()
{
cout<< "This is a 4 wheeler Vehicle"<<endl;
}
};
Class Car: public Vehicle, public FourWheeler
{
};
int main()
{
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
JCEI’s Jaihind College of Engineering, Kuran 2021-2022
Multilevel Inheritance:
In this type of inheritance the derived class inherits from a class, which in turn inherits from some
other class. The Super class for one, is sub class for the other.
// Multilevel Inheritance
#include <iostream>
using namespace std;
classVehicle
{
Public
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
Class fourWheeler : public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
Class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
int main()
{
Car obj;
return0;
}
Output:
This is a Vehicle
Objects with 4 wheels are vehicles
JCEI’s Jaihind College of Engineering, Kuran 2021-2022
Car has 4 Wheels
Hierarchical Inheritance:
In this type of inheritance, multiple derived classes inherits from a single base class.
// Hierarchical Inheritance
#include <iostream>
using namespace std;
classVehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
//Hybrid Inheritance
#include <iostream>
using namespace std;
classCar: publicVehicle
{
};
classBus: publicVehicle
{
};
intmain()
{
Car obj1;
Bus obj2;
return0;
}
Output:
This is a Vehicle
This is a Vehicle
Hybrid Inheritance:
#include <iostream>
using namespace std;
classVehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle"<<endl;
}
};
classFare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};
classCar: publicVehicle
{
};
classBus: publicVehicle, publicFare
{
};
int main({
Bus obj2;
return0;
}
Output:
This is a Vehicle
Fare of Vehicle
Exception Handling:
Exception handling is part of C++ and object oriented programming. they are added in C++ to handle
the unwanted situations during program execution. If we do not type the program correctly then ot might
result in errors. Main purpose of exception handling is to identify and report the runtime error in the
program.
Famous examples are divide by zero, array index out of bound error, file not found, device not found,
etc.
C++ exception handling is possible with three keywords iz. try, catch and throw. Exception handling
performs the following tasks:-
• Find the problem in the given code. It is also called as hit exception.
• It informs error has occurred. It is called as throwing the exception.
• We receive the roe info. It is called as catching the exception.
• It takes the corrective action. It is called as exception handling.
TRY:- It is block code in which there are chances of runtime error. This block is followed by one or
CATCH:- This is used to catch the exception thrown by the try block. In catch block we take corrective
action on throwing exception. If files are opened , we can take corrective action like closing file handles,
closing database connections, saving unsaved work ,etc.
THROW:- Program throws exception when problem occurs. It is possible with throw keyword.
SNYTAX:
// Exception Handling
Facilities:
1. Start.
2. Create classes Publication, book and tape.
3 . Publication class having data members title, price.
4. Class Book having data members pages and member functions getdata() and pudata().
5. Class Tape having data members minutes and member functions getdata() and pudata().
6. Create an object bof class book and object t of class tape.
7. Stop.
Input:
A class publication that stores the title (a string) and price (type float) of
publications. Derives two classes Book and Tape.
Output:
Display title and price from publication class. The result in following format:
Enter Title: OOP
Enter Price: 300
Enter Pages: 250
Enter Title: POP
Enter Price: 200
Enter Minutes: 60
Title: OOP
Price: 300
Pages: 250
Title: POP
Price: 200
Minutes: 60
# include<string.h>
private:
string title;
float price;
public:
void add()
cin.ignore();
getline(cin, title);
void display()
};
class book : public publication // declaring class book which inherits class publication in public mode.
private:
int page_count;
public:
void add_book()
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
{
try
add();
if (page_count <= 0)
throw page_count;
catch(...)
page_count = 0;
void display_book()
display();
};
class tape : public publication // declaring class tape which inherits class publication in public mode
private:
float play_time;
public:
void add_tape()
try
{
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
add();
if (play_time <= 0)
throw play_time;
catch(...)
play_time = 0;
void display_tape()
display();
};
int main()
do
switch(ch)
case 1:
b1[b_count].add_book();
b_count ++;
break;
case 2:
t1[t_count].add_tape();
t_count ++;
break;
case 3:
b1[j].display_book();
break;
case 4:
t1[j].display_tape();
break;
case 5:
exit(0);
return 0;
ubuntu@user:~$ ./a.out
MENU
5. Exit
MENU
5. Exit
MENU
5. Exit
MENU
5. Exit
MENU
5. Exit
Questions:
1. What is Inheritance?
2. What are types of Inheritance?
3. What is Single Inheritance?
4. What is Multiple Inheritance?
5. What is Hierarchical Inheritance?
6. What is Multilevel Inheritance?
7. What is Hybrid Inheritance?
8. What is Exception handling?
9. What are try catch block of exception handling?
Name
Roll No.
Date
Signature
Problem Statement:
Write a C++ program that creates an output file, writes information to it, closes the
file and open it again as an input file and read the information from the file.
Prerequisites:
Objectives:
Theory:
Stream:
A stream is a sequence of bytes. It acts as source from which the input data can be obtained or
as a destination to which the output data can be sent.
1. Input Stream
Input Streams are used to hold input from a data producer, such as a keyboard, a
file, or a network. The source stream that provides data to the program is called the
input stream. A program extracts the bytes from the input stream. In most cases the
standard input device is the keyboard. With the cin and “extraction” operator ( >>)
it is possible to read input from the keyboard.
2. Output Stream
Output Streams are used to hold output for a particular data consumer, such as a
monitor, a file, or a printer. The destination stream that receives data from the
program is called the output stream. A program inserts the bytes into an output
stream. By default, the standard output of a program points at the screen. So with
the cout operator and the “insertion” operator (<<) you can print a message onto the
screen.
iostream standard library provides cin and cout methods for reading from standard
input and writing to standard output respectively.
file handling provides three new datatypes:
ifstream This data type represents the input file stream and is used to read
information from files.
fstream This data type represents the file stream generally, and has the capabilities
of both ofstream and ifstream which means it can create files, write
information to files, and read information from files.
Opening a File
• A file must be opened before you can read from it or write toit.
• Either the ofstream or fstream object may be used to open a file for writing and
ifstream object is used to open a file for reading purpose only.
• Following is the standard syntax for open() function which is a member of fstream,
ifstream and ofstream objects.
void open(const char *filename, ios::openmode mode);
• Here, the first argument specifies the name and location of the file to be opened and
the second argument of the open() member function defines the mode in which the
file should be opened.
ios::ate Open a file for output and move the read/write control to the end
of the file.
You can combine two or more of these values by OR reading them together.
For example, if you want to open a file in write mode and want to
truncate it in case it already exists, following will be the syntax:
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
ofstream outfile;
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files
You read information from a file into your program using the stream
extraction operator (>>) just as you use that operator to input
information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of the cin
object.
Example
file .read ((char *)&V , sizeof (V)); file . Write ((char *)&V , sizeof (V));
These functions take two arguments. The first is the address of the
variable V , and the second is the length of that variable in bytes . The
address of variable must be cast to type char * (i.e pointer to character
type) .
1. Start
2. Create a class
Input:
how many record you want 3
1 abc
2 pqr
3 xyz
Output:
name=abc
Roll=1
name=pqr
Roll=2
name=xyz
Roll=3
Practical Program:
#include<fstream>
string Name;
int ID;
double salary;
public:
void accept()
cin.ignore();
getline(cin,Name);
cout<<"\n Id : ";
cin>>ID;
cin>>salary;
void display()
cout<<"\n Id : "<<ID;
};
int main()
Employee o[5];
fstream f;
f.open("demo2.txt",ios::out);
cin>>n;
for(i=0;i<n;i++)
o[i].accept();
f.write((char*)&o[i],sizeof o[i]);
f.close();
f.open("demo2.txt",ios::in);
for(i=0;i<n;i++)
cout<<"\nEmployee "<<i+1<<"\n";
f.read((char*)&o[i],sizeof o[i]);
o[i].display();
f.c lose();
return 0;
ubuntu@user:~$ ./a.out
Name : Omkar
Id : 234
Salary : 35000
Name : Abhishek
Id : 765
Salary : 48000
Employee 1
Name : Omkar
Id : 234
Salary : 35000
Employee 2
Name : Abhishek
Id : 765
Salary : 48000
Questions:
1. What is file handling?
Name
Roll No.
Date
Signature
Problem Statement:
Prerequisites:
Objectives:
Theory:
Templates
Templates are the foundation of generic programming, which involves writing code in a way
that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library
containers like iterators and algorithms are examples of generic programming and have been
developed using template concept. There is a single definition of each container, such as
vector, but we can define many different kinds of vectors for example, vector <int> or vector
<string>.
You can use templates to define functions as well as classes, let us see how do they work:
Function Template:
#include <iostream>
#include <string>
using namespace
std;
template <typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
int i = 39; int j = 20;
cout<< "Max(i, j): " << Max(i, j) <<endl; double f1 =13.5; double f2 =20.7;
cout<< "Max(f1, f2): " << Max(f1, f2) <<endl; string s1 = "Hello"; string s2 = "World";
cout<< "Max(s1, s2): " << Max(s1, s2) <<endl; return 0;
}
If we compile and run above code, this would produce the following result:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Template:
Just as we can define function b templates, we can also define class templates. The general
form of a generic class declaration is shown here:
template <class type> class class-name
{
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is instantiated.
You can define more than one generic data type by using a comma-separated list.
Following is the example to define class Stack<> and implement generic methods to push and pop the
elements from the stack:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T> class Stack
{
private:
vector<T>elems; // elements
public:
void push(T const&); //push element
voidpop(); // pop element
Ttop()const; // return top element bool empty()const
{ // return
true if empty.
returnelems.em
pty();
}
};
template <class T>
void Stack<T>::push (T const&elem)
{
// append copy of passed element
elems.push_back(elem);
}
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
template<class T>
void Stack<T>::pop ()
{
if (elems.empty())
{
throw out_of_range("Stack<>::pop(): empty stack");
}
// remove last element
elems.pop_back();
}
template <class T>
T Stack<T>::top () const
{
if (elems.empty())
{
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}
int main()
{
try
{
Stack<int> intStack; // stack of ints Stack<string>stringStack; // stack
ofstrings
// manipulate int stack int Stack.push(7);
cout<<intStack.top() <<endl;
// manipulate string stack stringStack.push("hello");
cout<<stringStack.top() <<std::endl; stringStack.pop();
stringStack.pop();
}
catch (exception const& ex)
{
cerr<< "Exception: " <<ex.what()
<<endl; return -1;
}
}
If we compile and run above code, this would produce the following result: 7
hello
Exception: Stack <> :: pop(): empty stack
Selection Sort:
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity,
making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort
is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain
situations, particularly where auxiliary memory is limited
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the lowest
value
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value
in the list, appears in the first position of sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in linear
Manner.
We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.
After two iterations, two least values are positioned at the beginning in the sorted manner.
The same process is applied on the rest of the items in the array.
Pictorial depiction of entire sorting process is as follows:
Algorithm:
1. Start
2. Declare the template parameter T.
3. Define template function for selection sort.
4. In main () Define two arrays, one for integer and another for float. and take a input
for both the arrays and call sorting function template to sort the number.
5. Stop
Input:
Output:
Sorted list= 3 5 7 8 9
Sorted list=2.2 3.8 5.5 6.7 9.4
int n;
#define size 10
template<class T>
int i,j,min;
T temp;
for(i=0;i<n-1;i++)
min=i;
for(j=i+1;j<n;j++)
if(A[j]<A[min])
min=j;
temp=A[i];
A[i]=A[min];
A[min]=temp;
cout<<"\nSorted array:";
for(i=0;i<n;i++)
cout<<" "<<A[i];
int main()
int A[size];
float B[size];
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
int i;
int ch;
do
cout<<"\n3. Exit";
cin>>ch;
switch(ch)
case 1:
cin>>n;
for(i=0;i<n;i++)
cin>>A[i];
sel(A);
break;
case 2:
cin>>n;
for(i=0;i<n;i++)
cin>>B[i];
}
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
sel(B);
break;
case 3:
exit(0);
}while(ch!=3);
return 0;
ubuntu@user:~$ ./a.out
MENU
1. Integer Values
2. Float Values
3. Exit
Sorted array: 2 4 5 6 7
MENU
1. Integer Values
2. Float Values
3. Exit
2.7
3.0
2.5
1.5
MENU
1. Integer Values
2. Float Values
3. Exit
Questions:
1. What is template?
2. What is Function template?
3. What is Class template?
4. Explain template with function overloading.
5. Explain template with non-type argument.
Name
Roll No.
Date
Signature
Title: Personnel information system using sorting and searching for STL and vector
container.
Problem Statement:
Write C++ program using STL for sorting and searching user defined records such as
personal records (Name, DOB, Telephone number etc) using vector container. OR
Write C++ program using STL for sorting and searching user defined records such as
Item records (Item code, name, cost, quantity etc) using vector container.
Prerequisites:
Objectives:
Theory:
STL:
The Standard Template Library (STL) is a set of C++ template classes to provide common programming
data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes,
algorithms, and iterators. It is a generalized library and so, its components are parameterized.
A working knowledge of template classes is a prerequisite for working with STL.
• Algorithms
• Containers
• Functions
• Iterators
Algorithms
Containers
• Containers or container classes store objects and data. There are in total seven standard “firstclass”
container classes and three container adaptor classes and only seven header files that provide access to
these containers or container adaptors.
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
Sequence Containers: implement data structures which can be accessed in a sequential manner.
• vector
• list
• deque
• arrays
• forward_list( Introduced in C++11)
• Container Adaptors: provide a different interface for sequential containers.
• queue
• priority_queue
• stack
• Associative Containers: implement sorted data structures that can be quickly searched (O(log
n) complexity).
• set
• multiset
• map
• multimap
• Unordered Associative Containers : implement unordered data structures that can be quickly searched
• unordered_set
• unordered_multiset
• unordered_map
• unordered_multimap
Functions
• The STL includees classes that overload the function call operator. Instances of such classes are called
function objects or functors. Functors allow the working of the associated function to be customized with
the help of parameters to be passed.
Iterators
• Asthe name suggests, iterators are used for working upon a sequence of values. They are the
major feature that allow generality in STL.
Utility Library
Sorting:
It is one of the most basic functions applied to data. It means arranging the data in a particular fashion,
which can be increasing or decreasing. There is a built in function in C++ STL by the name of sort().
This function internally uses Intro Sort. In more details it is implemented using hybrid of Quick Sort,
Heap Sort and Insertion Sort. By default, it uses Quick Sort but if Quick Sort is doing unfair partitioning
and taking more than N*log N time, it switches to Heap Sort and when the array size becomes really
small, it switches to Insertion Sort.
sort(startaddress, endaddress)
startaddress: the address of the first element of the array
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
endaddress: the address of the next contiguous location of the last element of the array.
So actually sort() sorts in the range of [startaddress , endaddress]
//Sorting
#include <iostream>
#include <algorithm>
using name space std;
void show (int a [])
{
for(inti = 0; i < 10; ++i)
cout<< a[i] << " ";
}
int main ()
{
int a [10] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
cout<< " \n The array before sorting is: ";
show(a);
sort(a, a+10);
cout<< "\n\n The array after sorting is: "; show(a);
return0;
}
The output of the above program is:
The array before sorting is: 1 5 8 9 6 7 3 4 2 0
The array after sorting is: 0 1 2 3 4 5 6 7 8 9
Searching:
It is a widely used searching algorithm that requires the array to be sorted before search is applied. The
main idea behind this algorithm is to keep dividing the array in half (divide and conquer) until the
element is found, or all the elements are exhausted.
It works by comparing the middle item of the array with our target, if it matches, it returns true otherwise
if the middle term is greater than the target, the search is performed in the left sub-array.
If the middle term is less than target, the search is performed in the right sub-array.
//Searching
#include <algorithm>
#include <iostream>
usingnamespacestd;
voidshow(inta[], intarraysize)
{
for(inti = 0; i <arraysize; ++i)
cout<< a[i] << " ";
}
intmain()
{
inta[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
intasize = sizeof(a) / sizeof(a[0]);
cout<< "\n The array is : ";
Output:
Facilities:
Algorithm:
1. Start.
2. Give a header file to use „vector‟.
3. Create a vector naming „personal_records‟.
4. Initialize variables to store name, birth date and telephone number.
5. Using iterator store as many records you want to store using predefined functions as
push_back().
6. Create another vector „item_record‟
7. Initialize variables to store item code, item name, quantity and cost.
8. Using iterator and predefined functions store the data.
9. Using predefined function sort (), sort the data stored according to user requirements.
10. Using predefined function search, search the element from the vector the user wants to check.
11. Display and call the functions using a menu.
12. End.
Input:
Output:
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
Display personnel information from database. The result in following format:
***** Menu *****
1. Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
Enter your choice:1
Enter Item Name: bat
Enter Item Quantity:2
Enter Item Cost:50
Enter Item Code:1
#include <algorithm> //The STL algorithms are generic because they can operate on a variety of data structures
#include <vector> //The header file for the STL vector library is vector.
public:
char name[10];
int quantity;
int cost;
int code;
bool operator==(const Item& i1) //Boolean operators allow you to create more complex conditional statements
if(code==i1.code) //operator will return 1 if the comparison is true, or 0 if the comparison is false
return 1;
return 0;
if(code<i1.code) //operator will return 1 if the comparison is true, or 0 if the comparison is false
return 1;
return 0;
};
vector<Item> o1;
void insert();
void search();
void dlt();
int main()
int ch;
do
cout<<"\n1.Insert";
cout<<"\n2.Display";
cout<<"\n3.Search";
cout<<"\n4.Sort";
cout<<"\n5.Delete";
cout<<"\n6.Exit";
cin>>ch;
switch(ch)
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
case 4:
sort(o1.begin(),o1.end(),compare);
display();
break;
case 5:
dlt();
break;
case 6:
exit(0);
}while(ch!=7);
return 0;
void insert()
Item i1;
cin>>i1.name;
cin>>i1.quantity;
cin>>i1.cost;
cin>>i1.code;
o1.push_back(i1);
void display()
for_each(o1.begin(),o1.end(),print);
{
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
cout<<"\n";
cout<<"\n\n";
void search()
vector<Item>::iterator p;
Item i1;
cin>>i1.code;
p=find(o1.begin(),o1.end(),i1);
if(p==o1.end())
cout<<"\nNot found!!!";
else
cout<<"\nFound!!!";
void dlt()
vector<Item>::iterator p;
Item i1;
cin>>i1.code;
p=find(o1.begin(),o1.end(),i1);
if(p==o1.end())
cout<<"\nNot found!!!";
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
}
else
o1.erase(p);
cout<<"\nDeleted!!!";
ubuntu@user:~$ ./a.out
* * * * * Menu * * * * *
1.Insert
2. Display
3.Search
4.Sort
5.Delete
6.Exit
* * * * * Menu * * * * *
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
* * * * * Menu * * * * *
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
* * * * * Menu * * * * *
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
Item Quantity : 3
Item Cost : 15
Item Quantity : 5
Item Cost : 25
Item Quantity : 3
Item Cost : 15
* * * * * Menu * * * * *
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
Not found!!!
* * * * * Menu * * * * *
1.Insert
2. Display
3. Search
4.Sort
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
5.Delete
6.Exit
Found!!!
* * * * * Menu * * * * *
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
Sorted on Cost :
Item Quantity : 3
Item Cost : 15
Item Quantity : 3
Item Cost : 15
Item Quantity : 5
Item Cost : 25
* * * * * Menu * * * * *
1.Insert
2. Display
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
3. Search
4.Sort
5.Delete
6.Exit
Deleted!!!
* * * * * Menu * * * * *
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
Item Quantity : 3
Item Cost : 15
Item Quantity : 5
Item Cost : 25
* * * * * Menu * * * * *
1.Insert
2.Display
3.Search
4.Sort
5.Delete
6.Exit
Hence, we have successfully studied the concept of STL(Standard Template Library) and how it
makes many data structures easy. It briefs about the predefined functions of STL and their uses such a
search() and sort()
Questions:
1. What is STL?
2. What are four components of STL?
3. What is Sorting?
4. What is Searching?
5. What vector container?
Name
Roll No.
Date
Signature
Problem Statement:
Write a program in C++ to use map associative container. The keys will be the names
of states and the values will be the populations of the states. When the program runs,
the user is prompted to type the name of a state. The program then looks in the map,
using the state name as an index and returns the population of the state.
Prerequisites:
Objectives:
Theory:
Map associative container are associative containers that store elements in a mapped fashion. Each
element has a key value and a mapped value. No two mapped values can have same key values.
map::operator[]
This operator is used to reference the element present at position given inside the operator. It is similar to
the at() function, the only difference is that the at() function throws an out-of-range exception when the
position is not in the bounds of the size of map, while this operator causes undefined behaviour.
Syntax :
mapname[key]
Parameters :
Returns :
Examples:
//Program
#include <map>
#include <iostream>
#include<string>
using name space std;
int main()
{
// map declaration
map<int,string>mymap;
// mapping integers to strings
mymap[1] = "Hi";
mymap[2] = "This";
mymap[3] = "is";
mymap[4] = "NBN";
// using operator[] to print string
// mapped to integer 4
cout<<mymap[4];
return0;
}
Output:
NBN
Facilities:
Algorithm:
1. Start.
2. Give a header file to map associative container.
3. Insert states name so that we get values as population of that state.
4. Use populationMap.insert().
5. Display the population of states.
6. End.
Input:
Output:
#include <map>
#include <string>
#include <utility>
int main()
mapType populationMap;
populationMap.insert(mapType::value_type("Bihar", 120));
populationMap.insert(make_pair("Rajasthan", 78));
populationMap.insert(make_pair("Odisha", 47));
populationMap.insert(make_pair("Kerala", 38));
populationMap.insert(make_pair("Telangana", 37));
populationMap.insert(make_pair("Assam", 35));
populationMap.insert(make_pair("Jharkhand", 38));
populationMap.insert(make_pair("Karnataka", 68));
populationMap.insert(make_pair("Gujarat", 70));
populationMap.insert(make_pair("Punjab", 31));
populationMap.insert(make_pair("Chhattisgarh", 30));
populationMap.insert(make_pair("Haryana", 29));
populationMap.insert(make_pair("Uttarakhand", 12));
populationMap.insert(make_pair("Tripura", 04));
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
populationMap.insert(make_pair("Meghalaya", 4));
populationMap.insert(make_pair("Manipur[", 3));
populationMap.insert(make_pair("Nagaland", 2));
populationMap.insert(make_pair("Goa", 2));
populationMap.insert(make_pair("Mizoram", 1));
populationMap.insert(make_pair("Sikkim", 1));
populationMap.insert(make_pair("UT Dadra and Nagar Haveli and Daman and Diu", 1));
populationMap.erase(iter);
cout << "Total state and UT of India with Size of populationMap: " << populationMap.size() << '\n';
char c;
do
string state;
cout<<"\nEnter that state you want to know the population of: ";
cin>>state;
iter = populationMap.find(state);
else
}while(c=='y'||c=='Y');
populationMap.clear();
return 0;
ubuntu@user:~$ ./a.out
Assam:35 million
Bihar:120 million
Chhattisgarh:30 million
Goa:2 million
Gujarat:70 million
Haryana:29 million
Jharkhand:38 million
Karnataka:68 million
Kerala:38 million
Maharashtra:125 million
Manipur[:3 million
Meghalaya:4 million
Mizoram:1 million
Nagaland:2 million
Odisha:47 million
Punjab:31 million
Rajasthan:78 million
Sikkim:1 million
Telangana:37 million
Tripura:4 million
UT Chandigarh:1 million
UT Delhi:19 million
JCEI’s Jaihind College of Engineering, Kuran 2020-2021
UT Jammu and Kashmir:14 million
UT Ladakh:0 million
UT Lakshadweep:0 million
UT Puducherry:2 million
Uttarakhand:12 million
Enter that state you want to know the population of: Maharashtra
Enter that state you want to know the population of: pune
Enter that state you want to know the population of: Sikkim
Questions: