The document discusses exception handling in C++. It provides information on key concepts like try, catch, and throw blocks. It also discusses exception classes in C++, defining custom exceptions, and how exceptions affect object destruction. Templates and the Standard Template Library (STL) are also covered at a high level.
in this tutorial we will discuss about
exception handling in C#
Exception class
creating user-defined exception
throw keyword
finally keyword
with examples'
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
in this tutorial we will discuss about
exception handling in C#
Exception class
creating user-defined exception
throw keyword
finally keyword
with examples'
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
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.
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;
}
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;
}