SlideShare a Scribd company logo
DISCOVER . LEARN . EMPOWER
UNIVERSITY INSTITUTE OF
COMPUTING
Master of Computer Applications
Winning Camp – Content
MCA (TPP) - 2021 Batch
Logic Building
*
*
*
3
Exception Handling in C++
An exception is a problem that arises during the execution of a program. A C++ exception is a response
to an exceptional circumstance that arises while a program is running, such as an attempt to divide by
zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is done using a throw
keyword.
catch − A program catches an exception with an exception handler at the place in a program where you
want to handle the problem. The catch keyword indicates the catching of an exception.
try − A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed even after
exception.
*
*
*
3
C++ Exception Classes
Exception Description
std::exception
It is an exception and parent class of
all standard C++ exceptions.
std::logic_failure
It is an exception that can be detected
by reading a code.
std::runtime_error
It is an exception that cannot be
detected by reading a code.
std::bad_exception
It is used to handle the unexpected
exceptions in a c++ program.
std::bad_cast
This exception is generally be thrown
by dynamic_cast.
std::bad_typeid
This exception is generally be thrown
by typeid.
std::bad_alloc
This exception is generally be thrown
by new.
*
*
*
3
Syntax of try-catch
try { // protected code }
catch( ExceptionName e1 )
{ // catch block }
catch( ExceptionName e2 )
{ // catch block }
catch( ExceptionName eN )
{ // catch block }
*
*
*
3
Throwing Exceptions
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
*
*
*
3
Example
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main () {
int x = 50; int y = 0; double z = 0;
try {
z = division(x, y);
cout << z << endl;
}
catch (const char* msg)
{ cerr << msg << endl; }
return 0;
}
*
*
*
3
Defining new Exceptions
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception {
const char * what () const throw () {
return "C++ Exception";
} };
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) { //Other errors
} }
*
*
*
3
Catch All Block
There is a special catch block called ‘catch all’ catch(…) that can be used to catch all types
of exceptions. For example, in the following program, an int is thrown as an exception, but
there is no catch block for int, so catch(…) block will be executed.
Example:
#include <iostream>
using namespace std;
int main() {
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exceptionn";
}
return 0;
}
*
*
*
3
Stack Unwinding
When we call some functions, it stores the address into call stack, and after coming back
from the functions, pops out the address to start the work where it was left of.
The stack unwinding is a process where the function call stack entries are removed at
runtime. To remove stack elements, we can use exceptions. If an exception is thrown from
the inner function, then all of the entries of the stack is removed, and return to the main
invoker function.
*
*
*
3
Working Example
#include <iostream>
using namespace std;
void function1() throw (int) { //this
function throws exception
cout<<"n Entering into function 1";
throw 100;
cout<<"n Exiting function 1";
}
void function2() throw (int) { //This
function calls function 1
cout<<"n Entering into function 2";
function1();
cout<<"n Exiting function 2";
}
void function3() { //function to call
function2, and handle
exception thrown by function1
cout<<"n Entering function 3 ";
try {
function2(); //try to execute function 2
}
catch(int i) {
cout<<"n Caught Exception: "<<i;
}
cout<<"n Exiting function 3";
}
int main() {
function3();
return 0;
}
*
*
*
3
Explanation
When function1() throws exception, its entry is removed from the function call stack,
because function1() doesn’t contain exception handler for the thrown exception, then next
entry in call stack is looked for exception handler.
The next entry is function2(). Since function2() also doesn’t have a handler, its entry is
also removed from the function call stack.
The next entry in the function call stack is function3(). Since function3() contains an
exception handler, the catch block inside function3() is executed, and finally, the code
after the catch block is executed.
*
*
*
3
Explanation
When function1() throws exception, its entry is removed from the function call stack,
because function1() doesn’t contain exception handler for the thrown exception, then next
entry in call stack is looked for exception handler.
The next entry is function2(). Since function2() also doesn’t have a handler, its entry is
also removed from the function call stack.
The next entry in the function call stack is function3(). Since function3() contains an
exception handler, the catch block inside function3() is executed, and finally, the code
after the catch block is executed.
*
*
*
3
Catching base and derived classes as
Exception
An Exception is an unwanted error or hurdle that a program throws while compiling.
There are various methods to handle an exception which is termed exceptional handling.
To catch base and derived classes as an exception in C++:
• If both base and derived classes are caught as exceptions, then the catch block of
the derived class must appear before the base class.
• If we put the base class first then the derived class catch block will never be
reached.
Algorithm
Begin
Declare a class B.
Declare another class D which inherits class B.
Declare an object of class D.
Try: throw derived.
Catch (D derived)
Print “Caught Derived Exception”.
Catch (B b)
Print “Caught Base Exception”.
End.
*
*
*
3
Catching base and derived classes as
Exception
#include <iostream>
using namespace std;
class Base {
};
class Derived : public Base {
};
int main()
{
Derived d;
// Some other functionalities
try {
// Monitored code
throw d;
}
catch (Base b) {
cout << "Caught Base Exception";
}
catch (Derived d) {
// This 'catch' block is NEVER
executed
cout << "Caught Derived
Exception";
}
getchar();
return 0;
}
Output:
prog.cpp: In function ‘int main()’:
prog.cpp:20:5: warning: exception of type ‘Derived’ will be caught
catch (Derived d) {
^
prog.cpp:17:5: warning: by earlier handler for ‘Base’
catch (Base b) {
*
*
*
3
Catching base and derived classes as
Exception
Following is the modified program and it prints “Caught Derived Exception”
#include <iostream>
using namespace std;
class Base {};
class Derived : public Base {};
int main()
{
Derived d;
// Some other functionalities
try {
// Monitored code
throw d;
}
catch (Derived d) {
cout << "Caught Derived Exception";
}
catch (Base b) {
cout << "Caught Base Exception";
}
getchar(); // To read the next character
return 0;
}
*
*
*
3
Catch Block and type Conversion
#include <iostream>
using namespace std;
int main() {
try{
throw 'a';
}
catch(int a) {
cout << "Integer value is caught :" << a;
}
catch(...) {
cout << "Entering into default catch block";
}
}
Output:
Entering into default catch block
As we can see the character ‘a’ is thrown, but
the first catch block is for int. If we think that
the ASCII of ‘a’ is an integer, so will be
entering into the first block, but that kind of
conversions are not applicable for the catch
blocks.
*
*
*
3
Catch Block and type Conversion
#include <iostream>
using namespace std;
class TestExcept1 {};
class TestExcept2 {
public:
TestExcept2 (const TestExcept1 &e ){
// Defining the Conversion constructor
cout << "From the Conversion constructor";
}
};
main() {
try{
TestExcept1 exp1;
throw exp1;
} catch(TestExcept2 e2) {
cout << "Caught TestExcept2 " << endl;
} catch(...) {
cout << "Entering into default catch block " << endl;
}
}
Output:
Entering into default catch block
The derived type objects are not converted to the
base type objects while the derived type objects are
thrown.
*
*
*
3
Exception handling and object
destruction
• An object is termed as an instance of the class which has the same name
as that of the class.
• A destructor is a member function of a class that has the same name as
that of the class but is preceded by a ‘~’ (tilde) sign, also it is
automatically called after the scope of the code runs out. The practice of
pulverizing or demolition of the existing object memory is termed object
destruction.
• In other words, the class of the program never holds any kind of memory
or storage, it is the object which holds the memory or storage and to
deallocate/destroy the memory of created object we use destructors.
• When an exception is thrown in the class, the destructor is called
automatically before the catch block gets executed.
*
*
*
3
Exception handling and object
destruction
#include <iostream>
using namespace std;
// Initialization of class
class Test {
public:
// Constructor of class
Test()
{
cout << "Constructing an object of
class Test "
<< endl;
}
// Destructor of class
~Test()
{
cout << "Destructing the object of class Test "
<< endl;
}
};
int main()
{
try {
// Calling the constructor
Test t1;
throw 10;
} // Destructor is being called here
// Before the 'catch' statement
catch (int i) {
cout << "Caught " << i << endl;
}
}
*
*
*
3
Template Functions and Classes
• A template is a simple and yet very powerful tool in C++. The simple idea is to pass
data type as a parameter so that we don’t need to write the same code for different data
types. For example, a software company may need sort() for different data types.
Rather than writing and maintaining the multiple codes, we can write one sort() and
pass data type as a parameter.
• C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The
second keyword can always be replaced by keyword ‘class’.
• There are two ways we can implement templates:
• Function Templates
• Class Templates
• Similar to function templates, we can use class templates to create a single class to
work with different data types.
• Class templates come in handy as they can make our code shorter and more
manageable.
*
*
*
3
Template Functions and Classes
• Templates are expanded at compiler time. This is like macros. The difference is, the
compiler does type checking before template expansion. The idea is simple, source
code contains only function/class, but compiled code may contain multiple copies of
same function/class.
*
*
*
3
Class Template
• A class template starts with the keyword template followed by template parameter(s)
inside < > which is followed by the class declaration.
• Syntax
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};
Creating a Class Template Object
Once we've declared and defined a class template, we can create its objects in other classes
or functions (such as the main() function) with the following syntax
className<dataType> classObject;
*
*
*
3
Class Template Example
#include <iostream>
using namespace std;
// Class template
template <class T>
class Number {
private:
// Variable of type T
T num;
public:
Number(T n) : num(n) {} // constructor
T getNum() {
return num;
}
};
int main() {
// create object with int type
Number<int> numberInt(7);
// create object with double type
Number<double> numberDouble(7.7);
cout << "int Number = " <<
numberInt.getNum() << endl;
cout << "double Number = " <<
numberDouble.getNum() << endl;
return 0;
}
*
*
*
3
Templates With Multiple Parameters
#include <iostream>
using namespace std;
// Class template with multiple and default
parameters
template <class T, class U, class V = char>
class ClassTemplate {
private:
T var1;
U var2;
V var3;
public:
ClassTemplate(T v1, U v2, V v3) : var1(v1),
var2(v2), var3(v3) {} // constructor
void printVar() {
cout << "var1 = " << var1 << endl;
cout << "var2 = " << var2 << endl;
cout << "var3 = " << var3 << endl;
}
};
int main() {
// create object with int, double and char
types
ClassTemplate<int, double> obj1(7, 7.7,
'c');
cout << "obj1 values: " << endl;
obj1.printVar();
// create object with int, double and bool
types
ClassTemplate<double, char, bool>
obj2(8.8, 'a', false);
cout << "nobj2 values: " << endl;
obj2.printVar();
return 0;
}
*
*
*
3
Function Templates
#include <iostream>
using namespace std;
// One function works for all data types. This
would work
// even for user defined types if operator '>' is
overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call
myMax for int
cout << myMax<double>(3.0, 7.0)
<< endl; // call myMax for double
cout << myMax<char>('g', 'e')
<< endl; // call myMax for char
return 0;
}
*
*
*
3
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.
• STL has four components
1. Algorithms
2. Containers
3. Functions
4. Iterators
*
*
*
3
Containers
• In C++, there are generally 3 kinds of STL containers:
• Sequential Containers
• Array, Vector, Deque, List, Forward List
• Associative Containers
• set, multiset, map, multimap
• Unordered Associative Containers
• unordered_set (Introduced in C++11)
• unordered_multiset (Introduced in C++11)
• unordered_map (Introduced in C++11)
• unordered_multimap (Introduced in C++11)
*
*
*
3
Containers Example (Vector)
#include <iostream>
#include <vector>
using namespace std;
int main() {
// initialize a vector of int type
vector<int> numbers = {1, 100, 10, 70, 100};
// print the vector
cout << "Numbers are: ";
for(auto &num: numbers) {
cout << num << ", ";
}
return 0;
}
*
*
*
3
Containers Example (Set)
#include <iostream>
#include <vector>
using namespace std;
int main() {
// initialize a vector of int type
vector<int> numbers = {1, 100, 10, 70, 100};
// print the vector
cout << "Numbers are: ";
for(auto &num: numbers) {
cout << num << ", ";
}
return 0;
}
*
*
*
3
Containers Example (Unordered_set)
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
// initialize an unordered_set of int type
unordered_set<int> numbers = {1, 100, 10, 70, 100};
// print the set
cout << "Numbers are: ";
for(auto &num: numbers) {
cout << num << ", ";
}
return 0;
}
*
*
*
3
Containers Adaptor Example (stack)
#include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of ints
stack<int> numbers;
// push into stack
numbers.push(1);
numbers.push(100);
numbers.push(10);
cout << "Numbers are: ";
// we can access the element by getting
the top and popping
// until the stack is empty
while(!numbers.empty()) {
// print top element
cout << numbers.top() << ", ";
// pop top element from stack
numbers.pop();
}
return 0;
}
*
*
*
3
C++ Iterators
Iterators are just like pointers used to access the container elements.
Important Points:
• Iterators are used to traverse from one element to another element, a process is known
as iterating through the container.
• The main advantage of an iterator is to provide a common interface for all the
containers type.
• Iterators make the algorithm independent of the type of the container used.
• Iterators provide a generic approach to navigate through the elements of a container.
Syntax:
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;
*
*
*
3
Operations performed on Iterator
• Operator (*) : The '*' operator returns the element of the current position pointed by the
iterator.
• Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator
points to the next element of the container.
• Operator (==) and Operator (!=) : Both these operators determine whether the two
iterators point to the same position or not.
• Operator (=) : The '=' operator assigns the iterator.
*
*
*
3
Input Iterator
An input iterator is an iterator used to access the elements from the container, but it does
not modify the value of a container.
Operators used for an input iterator are:
Increment operator(++)
Equal operator(==)
Not equal operator(!=)
Dereference operator(*)
*
*
*
3
Output Iterator
An output iterator is an iterator used to modify the value of a container, but it does not read
the value from a container. Therefore, we can say that an output iterator is a write-only
iterator.
Operators used for an output iterator are:
Increment operator(++)
Assignment operator(=)
*
*
*
3
Forward Iterator
A forward iterator is an iterator used to read and write to a container. It is a multi-pass
iterator.
Operators used for a Forward iterator are:
Increment operator(++)
Assignment operator(=)
Equal operator(=)
Not equal operator(!=)
*
*
*
3
Bidirectional Iterator
A bidirectional iterator is an iterator supports all the features of a forward iterator plus it
adds one more feature, i.e., decrement operator(--). We can move backward by
decrementing an iterator.
Operators used for a Bidirectional iterator are:
Increment operator(++)
Assignment operator(=)
Equal operator(=)
Not equal operator(!=)
Decrement operator(--)
*
*
*
3
Random Access Iterator
A Random Access iterator is an iterator provides random access of an element at an
arbitrary location. It has all the features of a bidirectional iterator plus it adds one more
feature, i.e., pointer addition and pointer subtraction to provide random access to an
element.
Providers of Iterators
Iterator categories Provider
Input iterator istream
Output iterator ostream
Forward iterator
Bidirectional iterator List, set, multiset, map, multimap
Random access iterator Vector, deque, array
*
*
*
3
Examples
begin() and end()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
// Declaring iterator to a vector
vector<int>::iterator ptr;
cout << "The vector elements are : ";
for (ptr = ar.begin(); ptr < ar.end(); ptr++)
cout << *ptr << " ";
return 0;
}
*
*
*
3
Examples
advance() :- This function is used to increment the iterator position till the specified
number mentioned in its arguments.
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
vector<int>::iterator ptr = ar.begin();
advance(ptr, 3);
cout << "The position of iterator after advancing is : ";
cout << *ptr << " ";
return 0;
}
*
*
*
3
Examples
next() :- This function returns the new iterator that the iterator would point after advancing
the positions mentioned in its arguments.
prev() :- This function returns the new iterator that the iterator would point after
decrementing the positions mentioned in its arguments.
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
vector<int>::iterator ptr = ar.begin();
vector<int>::iterator ftr = ar.end();
auto it = next(ptr, 3);
auto it1 = prev(ftr, 3);
cout << "The position of new iterator using next() is : ";
cout << *it << " ";
cout << endl;
cout << "The position of new iterator using prev() is : ";
cout << *it1 << " ";
cout << endl;
return 0;
}
*
*
*
3
Examples
inserter() :- This function is used to insert the elements at any position in the container. It
accepts 2 arguments, the container and iterator to position where the elements have to be
inserted.
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
vector<int> ar1 = {10, 20, 30};
vector<int>::iterator ptr = ar.begin();
advance(ptr, 3);
// copying 1 vector elements in other using inserter()
// inserts ar1 after 3rd position in ar
copy(ar1.begin(), ar1.end(), inserter(ar,ptr));
// Displaying new vector elements
cout << "The new vector after inserting elements is : ";
for (int &x : ar)
cout << x << " ";
return 0;
}
THANK YOU

More Related Content

Similar to 6-Exception Handling and Templates.pptx

Object Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptxObject Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptx
RashidFaridChishti
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++
IRJET Journal
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
junnubabu
 
Oop10 6
Oop10 6Oop10 6
Oop10 6schwaa
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exceptions ref
Exceptions refExceptions ref
Exceptions ref. .
 
Catch and throw blocks
Catch and throw blocksCatch and throw blocks
Catch and throw blocks
ashrafkhan12345
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
ppd1961
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
Exception handling
Exception handlingException handling
Exception handling
priyaankasrivastavaa
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
Rajan Shah
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
Abid Kohistani
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
madan r
 
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Abu Saleh
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 

Similar to 6-Exception Handling and Templates.pptx (20)

Object Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptxObject Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptx
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Oop10 6
Oop10 6Oop10 6
Oop10 6
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exceptions ref
Exceptions refExceptions ref
Exceptions ref
 
Catch and throw blocks
Catch and throw blocksCatch and throw blocks
Catch and throw blocks
 
Handling
HandlingHandling
Handling
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 

Recently uploaded

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 

Recently uploaded (20)

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 

6-Exception Handling and Templates.pptx

  • 1. DISCOVER . LEARN . EMPOWER UNIVERSITY INSTITUTE OF COMPUTING Master of Computer Applications Winning Camp – Content MCA (TPP) - 2021 Batch Logic Building
  • 2. * * * 3 Exception Handling in C++ An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. Advantage It maintains the normal flow of the application. In such case, rest of the code is executed even after exception.
  • 3. * * * 3 C++ Exception Classes Exception Description std::exception It is an exception and parent class of all standard C++ exceptions. std::logic_failure It is an exception that can be detected by reading a code. std::runtime_error It is an exception that cannot be detected by reading a code. std::bad_exception It is used to handle the unexpected exceptions in a c++ program. std::bad_cast This exception is generally be thrown by dynamic_cast. std::bad_typeid This exception is generally be thrown by typeid. std::bad_alloc This exception is generally be thrown by new.
  • 4. * * * 3 Syntax of try-catch try { // protected code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block }
  • 5. * * * 3 Throwing Exceptions double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); }
  • 6. * * * 3 Example #include <iostream> using namespace std; double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); } int main () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; } catch (const char* msg) { cerr << msg << endl; } return 0; }
  • 7. * * * 3 Defining new Exceptions #include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } }; int main() { try { throw MyException(); } catch(MyException& e) { std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl; } catch(std::exception& e) { //Other errors } }
  • 8. * * * 3 Catch All Block There is a special catch block called ‘catch all’ catch(…) that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so catch(…) block will be executed. Example: #include <iostream> using namespace std; int main() { try { throw 10; } catch (char *excp) { cout << "Caught " << excp; } catch (...) { cout << "Default Exceptionn"; } return 0; }
  • 9. * * * 3 Stack Unwinding When we call some functions, it stores the address into call stack, and after coming back from the functions, pops out the address to start the work where it was left of. The stack unwinding is a process where the function call stack entries are removed at runtime. To remove stack elements, we can use exceptions. If an exception is thrown from the inner function, then all of the entries of the stack is removed, and return to the main invoker function.
  • 10. * * * 3 Working Example #include <iostream> using namespace std; void function1() throw (int) { //this function throws exception cout<<"n Entering into function 1"; throw 100; cout<<"n Exiting function 1"; } void function2() throw (int) { //This function calls function 1 cout<<"n Entering into function 2"; function1(); cout<<"n Exiting function 2"; } void function3() { //function to call function2, and handle exception thrown by function1 cout<<"n Entering function 3 "; try { function2(); //try to execute function 2 } catch(int i) { cout<<"n Caught Exception: "<<i; } cout<<"n Exiting function 3"; } int main() { function3(); return 0; }
  • 11. * * * 3 Explanation When function1() throws exception, its entry is removed from the function call stack, because function1() doesn’t contain exception handler for the thrown exception, then next entry in call stack is looked for exception handler. The next entry is function2(). Since function2() also doesn’t have a handler, its entry is also removed from the function call stack. The next entry in the function call stack is function3(). Since function3() contains an exception handler, the catch block inside function3() is executed, and finally, the code after the catch block is executed.
  • 12. * * * 3 Explanation When function1() throws exception, its entry is removed from the function call stack, because function1() doesn’t contain exception handler for the thrown exception, then next entry in call stack is looked for exception handler. The next entry is function2(). Since function2() also doesn’t have a handler, its entry is also removed from the function call stack. The next entry in the function call stack is function3(). Since function3() contains an exception handler, the catch block inside function3() is executed, and finally, the code after the catch block is executed.
  • 13. * * * 3 Catching base and derived classes as Exception An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. To catch base and derived classes as an exception in C++: • If both base and derived classes are caught as exceptions, then the catch block of the derived class must appear before the base class. • If we put the base class first then the derived class catch block will never be reached. Algorithm Begin Declare a class B. Declare another class D which inherits class B. Declare an object of class D. Try: throw derived. Catch (D derived) Print “Caught Derived Exception”. Catch (B b) Print “Caught Base Exception”. End.
  • 14. * * * 3 Catching base and derived classes as Exception #include <iostream> using namespace std; class Base { }; class Derived : public Base { }; int main() { Derived d; // Some other functionalities try { // Monitored code throw d; } catch (Base b) { cout << "Caught Base Exception"; } catch (Derived d) { // This 'catch' block is NEVER executed cout << "Caught Derived Exception"; } getchar(); return 0; } Output: prog.cpp: In function ‘int main()’: prog.cpp:20:5: warning: exception of type ‘Derived’ will be caught catch (Derived d) { ^ prog.cpp:17:5: warning: by earlier handler for ‘Base’ catch (Base b) {
  • 15. * * * 3 Catching base and derived classes as Exception Following is the modified program and it prints “Caught Derived Exception” #include <iostream> using namespace std; class Base {}; class Derived : public Base {}; int main() { Derived d; // Some other functionalities try { // Monitored code throw d; } catch (Derived d) { cout << "Caught Derived Exception"; } catch (Base b) { cout << "Caught Base Exception"; } getchar(); // To read the next character return 0; }
  • 16. * * * 3 Catch Block and type Conversion #include <iostream> using namespace std; int main() { try{ throw 'a'; } catch(int a) { cout << "Integer value is caught :" << a; } catch(...) { cout << "Entering into default catch block"; } } Output: Entering into default catch block As we can see the character ‘a’ is thrown, but the first catch block is for int. If we think that the ASCII of ‘a’ is an integer, so will be entering into the first block, but that kind of conversions are not applicable for the catch blocks.
  • 17. * * * 3 Catch Block and type Conversion #include <iostream> using namespace std; class TestExcept1 {}; class TestExcept2 { public: TestExcept2 (const TestExcept1 &e ){ // Defining the Conversion constructor cout << "From the Conversion constructor"; } }; main() { try{ TestExcept1 exp1; throw exp1; } catch(TestExcept2 e2) { cout << "Caught TestExcept2 " << endl; } catch(...) { cout << "Entering into default catch block " << endl; } } Output: Entering into default catch block The derived type objects are not converted to the base type objects while the derived type objects are thrown.
  • 18. * * * 3 Exception handling and object destruction • An object is termed as an instance of the class which has the same name as that of the class. • A destructor is a member function of a class that has the same name as that of the class but is preceded by a ‘~’ (tilde) sign, also it is automatically called after the scope of the code runs out. The practice of pulverizing or demolition of the existing object memory is termed object destruction. • In other words, the class of the program never holds any kind of memory or storage, it is the object which holds the memory or storage and to deallocate/destroy the memory of created object we use destructors. • When an exception is thrown in the class, the destructor is called automatically before the catch block gets executed.
  • 19. * * * 3 Exception handling and object destruction #include <iostream> using namespace std; // Initialization of class class Test { public: // Constructor of class Test() { cout << "Constructing an object of class Test " << endl; } // Destructor of class ~Test() { cout << "Destructing the object of class Test " << endl; } }; int main() { try { // Calling the constructor Test t1; throw 10; } // Destructor is being called here // Before the 'catch' statement catch (int i) { cout << "Caught " << i << endl; } }
  • 20. * * * 3 Template Functions and Classes • A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. • C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’. • There are two ways we can implement templates: • Function Templates • Class Templates • Similar to function templates, we can use class templates to create a single class to work with different data types. • Class templates come in handy as they can make our code shorter and more manageable.
  • 21. * * * 3 Template Functions and Classes • Templates are expanded at compiler time. This is like macros. The difference is, the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of same function/class.
  • 22. * * * 3 Class Template • A class template starts with the keyword template followed by template parameter(s) inside < > which is followed by the class declaration. • Syntax template <class T> class className { private: T var; ... .. ... public: T functionName(T arg); ... .. ... }; Creating a Class Template Object Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax className<dataType> classObject;
  • 23. * * * 3 Class Template Example #include <iostream> using namespace std; // Class template template <class T> class Number { private: // Variable of type T T num; public: Number(T n) : num(n) {} // constructor T getNum() { return num; } }; int main() { // create object with int type Number<int> numberInt(7); // create object with double type Number<double> numberDouble(7.7); cout << "int Number = " << numberInt.getNum() << endl; cout << "double Number = " << numberDouble.getNum() << endl; return 0; }
  • 24. * * * 3 Templates With Multiple Parameters #include <iostream> using namespace std; // Class template with multiple and default parameters template <class T, class U, class V = char> class ClassTemplate { private: T var1; U var2; V var3; public: ClassTemplate(T v1, U v2, V v3) : var1(v1), var2(v2), var3(v3) {} // constructor void printVar() { cout << "var1 = " << var1 << endl; cout << "var2 = " << var2 << endl; cout << "var3 = " << var3 << endl; } }; int main() { // create object with int, double and char types ClassTemplate<int, double> obj1(7, 7.7, 'c'); cout << "obj1 values: " << endl; obj1.printVar(); // create object with int, double and bool types ClassTemplate<double, char, bool> obj2(8.8, 'a', false); cout << "nobj2 values: " << endl; obj2.printVar(); return 0; }
  • 25. * * * 3 Function Templates #include <iostream> using namespace std; // One function works for all data types. This would work // even for user defined types if operator '>' is overloaded template <typename T> T myMax(T x, T y) { return (x > y) ? x : y; } int main() { cout << myMax<int>(3, 7) << endl; // Call myMax for int cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double cout << myMax<char>('g', 'e') << endl; // call myMax for char return 0; }
  • 26. * * * 3 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. • STL has four components 1. Algorithms 2. Containers 3. Functions 4. Iterators
  • 27. * * * 3 Containers • In C++, there are generally 3 kinds of STL containers: • Sequential Containers • Array, Vector, Deque, List, Forward List • Associative Containers • set, multiset, map, multimap • Unordered Associative Containers • unordered_set (Introduced in C++11) • unordered_multiset (Introduced in C++11) • unordered_map (Introduced in C++11) • unordered_multimap (Introduced in C++11)
  • 28. * * * 3 Containers Example (Vector) #include <iostream> #include <vector> using namespace std; int main() { // initialize a vector of int type vector<int> numbers = {1, 100, 10, 70, 100}; // print the vector cout << "Numbers are: "; for(auto &num: numbers) { cout << num << ", "; } return 0; }
  • 29. * * * 3 Containers Example (Set) #include <iostream> #include <vector> using namespace std; int main() { // initialize a vector of int type vector<int> numbers = {1, 100, 10, 70, 100}; // print the vector cout << "Numbers are: "; for(auto &num: numbers) { cout << num << ", "; } return 0; }
  • 30. * * * 3 Containers Example (Unordered_set) #include <iostream> #include <unordered_set> using namespace std; int main() { // initialize an unordered_set of int type unordered_set<int> numbers = {1, 100, 10, 70, 100}; // print the set cout << "Numbers are: "; for(auto &num: numbers) { cout << num << ", "; } return 0; }
  • 31. * * * 3 Containers Adaptor Example (stack) #include <iostream> #include <stack> using namespace std; int main() { // create a stack of ints stack<int> numbers; // push into stack numbers.push(1); numbers.push(100); numbers.push(10); cout << "Numbers are: "; // we can access the element by getting the top and popping // until the stack is empty while(!numbers.empty()) { // print top element cout << numbers.top() << ", "; // pop top element from stack numbers.pop(); } return 0; }
  • 32. * * * 3 C++ Iterators Iterators are just like pointers used to access the container elements. Important Points: • Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used. • Iterators provide a generic approach to navigate through the elements of a container. Syntax: <ContainerType> :: iterator; <ContainerType> :: const_iterator;
  • 33. * * * 3 Operations performed on Iterator • Operator (*) : The '*' operator returns the element of the current position pointed by the iterator. • Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator points to the next element of the container. • Operator (==) and Operator (!=) : Both these operators determine whether the two iterators point to the same position or not. • Operator (=) : The '=' operator assigns the iterator.
  • 34. * * * 3 Input Iterator An input iterator is an iterator used to access the elements from the container, but it does not modify the value of a container. Operators used for an input iterator are: Increment operator(++) Equal operator(==) Not equal operator(!=) Dereference operator(*)
  • 35. * * * 3 Output Iterator An output iterator is an iterator used to modify the value of a container, but it does not read the value from a container. Therefore, we can say that an output iterator is a write-only iterator. Operators used for an output iterator are: Increment operator(++) Assignment operator(=)
  • 36. * * * 3 Forward Iterator A forward iterator is an iterator used to read and write to a container. It is a multi-pass iterator. Operators used for a Forward iterator are: Increment operator(++) Assignment operator(=) Equal operator(=) Not equal operator(!=)
  • 37. * * * 3 Bidirectional Iterator A bidirectional iterator is an iterator supports all the features of a forward iterator plus it adds one more feature, i.e., decrement operator(--). We can move backward by decrementing an iterator. Operators used for a Bidirectional iterator are: Increment operator(++) Assignment operator(=) Equal operator(=) Not equal operator(!=) Decrement operator(--)
  • 38. * * * 3 Random Access Iterator A Random Access iterator is an iterator provides random access of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it adds one more feature, i.e., pointer addition and pointer subtraction to provide random access to an element. Providers of Iterators Iterator categories Provider Input iterator istream Output iterator ostream Forward iterator Bidirectional iterator List, set, multiset, map, multimap Random access iterator Vector, deque, array
  • 39. * * * 3 Examples begin() and end() #include<iostream> #include<iterator> // for iterators #include<vector> // for vectors using namespace std; int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterator to a vector vector<int>::iterator ptr; cout << "The vector elements are : "; for (ptr = ar.begin(); ptr < ar.end(); ptr++) cout << *ptr << " "; return 0; }
  • 40. * * * 3 Examples advance() :- This function is used to increment the iterator position till the specified number mentioned in its arguments. #include<iostream> #include<iterator> // for iterators #include<vector> // for vectors using namespace std; int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; vector<int>::iterator ptr = ar.begin(); advance(ptr, 3); cout << "The position of iterator after advancing is : "; cout << *ptr << " "; return 0; }
  • 41. * * * 3 Examples next() :- This function returns the new iterator that the iterator would point after advancing the positions mentioned in its arguments. prev() :- This function returns the new iterator that the iterator would point after decrementing the positions mentioned in its arguments. #include<iostream> #include<iterator> // for iterators #include<vector> // for vectors using namespace std; int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; vector<int>::iterator ptr = ar.begin(); vector<int>::iterator ftr = ar.end(); auto it = next(ptr, 3); auto it1 = prev(ftr, 3); cout << "The position of new iterator using next() is : "; cout << *it << " "; cout << endl; cout << "The position of new iterator using prev() is : "; cout << *it1 << " "; cout << endl; return 0; }
  • 42. * * * 3 Examples inserter() :- This function is used to insert the elements at any position in the container. It accepts 2 arguments, the container and iterator to position where the elements have to be inserted. #include<iostream> #include<iterator> // for iterators #include<vector> // for vectors using namespace std; int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; vector<int> ar1 = {10, 20, 30}; vector<int>::iterator ptr = ar.begin(); advance(ptr, 3); // copying 1 vector elements in other using inserter() // inserts ar1 after 3rd position in ar copy(ar1.begin(), ar1.end(), inserter(ar,ptr)); // Displaying new vector elements cout << "The new vector after inserting elements is : "; for (int &x : ar) cout << x << " "; return 0; }