You are on page 1of 80

OBJECT ORIENTED DESIGN

AND PROGRAMMING
(CODE: 21CSC101T)
2nd Semester, B. Tech
2023-2024
UNIT-5

Mr. Bapuji Rao


Assistant Professor
Department of CSE
UNIT – 5
2

 STL

SRM IST, DELHI-NCR CAMPUS


 Containers – Sequence and Associative Container
 Sequence Containers – Vector, List, Deque, Array, Stack
 Associative Containers – Map, Multimap
 Iterator and Specialized Iterators
 Functions of Iterator
 Algorithms – find( ), count( ), sort( )
 Algorithms – search( ), merge( ), for_each( ), transform( )

Mr. BAPUJI RAO, Dept. of CSE


STL
3

 A collection of generic classes and functions is called the Standard Template


Library(STL).

SRM IST, DELHI-NCR CAMPUS


 STL components are part of the C++ standard library.
 STL components are defined in the "namespace std".
 To use STL in the program, we must include "using namespace std"
directive.
 This directive informs the compiler that we intend to use the STL.

Mr. BAPUJI RAO, Dept. of CSE


COMPONENTS
4

 The three key components of STL are:


• Containers

SRM IST, DELHI-NCR CAMPUS


• Algorithms
• Iterators

CONTAINER

ALGORITHM ITERATOR CONTAINER

CONTAINER

Mr. BAPUJI RAO, Dept. of CSE


CONTAINER
5

 A container is a collection of objects and these objects actually stores data.


 These containers are implemented by template classes and therefore can be

SRM IST, DELHI-NCR CAMPUS


easily customized to hold different types of data.

Mr. BAPUJI RAO, Dept. of CSE


ALGORITHM
6

 An algorithm is a procedure that is used to process the data contained in the

SRM IST, DELHI-NCR CAMPUS


objects which is resided in the container.
 Algorithms are implemented by the template functions.
 It supports different types of tasks such as initializing, searching, copying,
sorting, and merging.

Mr. BAPUJI RAO, Dept. of CSE


ITERATOR
7

 An Iterator is an object that points to an object in a container.


 It acts just like a pointer.

SRM IST, DELHI-NCR CAMPUS


 Each of the container classes is associated with a type of iterator.
 Each of the STL algorithms uses a certain type of iterator.
 Iterators connect the algorithms and containers and play an important role in
the manipulation of dada stored in the objects in a container.
 Algorithms employ Iterators to perform operations stored in containers.

Mr. BAPUJI RAO, Dept. of CSE


ITERATOR
8

ITERATOR DESCRIPTION
Read values with forward movement.
input_iterator
It can be incremented, compared, and dereferenced.

SRM IST, DELHI-NCR CAMPUS


Write values with forward movement.
output_iterator
It can be incremented and dereferenced.
forward_iterator Read or write values with forward movement.
Either a random iterator or a bidirectional iterator that moves in reverse
reverse_iterator
direction.
random_iterator Read and write values with random access.
Read and write values with forward and backward movement.
bidirectional_iterator
It is like the forward iterators, but you can increment and decrement them.

Mr. BAPUJI RAO, Dept. of CSE


CLASSIFICATION OF CONTAINERS
9

DERIVED CONTAINERS
(OR)

SRM IST, DELHI-NCR CAMPUS


SEQUENCE CONTAINERS ASSOCIATIVE CONTAINERS CONTAINER ADAPTORS

VECTOR LIST DEQUEUE SET MULTISET MAP MULTIMAP STACK QUEUE PRIORITY
QUEUE

Mr. BAPUJI RAO, Dept. of CSE


SEQUENCE CONTAINERS
10

SEQUENCE HEADER
DESCRIPTION ITERATOR
CONTAINERS FILE
 A dynamic array.

SRM IST, DELHI-NCR CAMPUS


Vector  The insertion and deletion takes place at <vector> Random Access
the rear end of the array.
 A bi-directional linear list.
List  The insertion and deletion takes place <list> Bi-directional
anywhere in the array.
 A double ended queue.
Random Access
Dequeue  The insertion and deletion takes place at <deque>
both the end of the array.

Mr. BAPUJI RAO, Dept. of CSE


ASSOCIATIVE CONTAINERS
11

ASSOCIATIVE HEADER
DESCRIPTION ITERATOR
CONTAINERS FILE
 A set stores unique (no duplicate) set of

SRM IST, DELHI-NCR CAMPUS


Set values. <set> Bi-directional
 It allows for rapid look up.
 A multi-set stores non-unique (duplicate) set
Multiset <set> Bi-directional
of values.
 It stores unique key : value pairs in a set.
Map  Each key is associated with only one value. <map> Bi-directional

 It stores unique key : value pairs in a set.


Multimap  Each key may be associated with more than <map> Bi-directional
one value.
Mr. BAPUJI RAO, Dept. of CSE
DERIVED CONTAINERS
12

DERIVED HEADER
DESCRIPTION ITERATOR
CONTAINERS FILE
 A standard stack.

SRM IST, DELHI-NCR CAMPUS


 It is LIFO(Last In First Out), i.e., the
Stack <stack> No Iterator
element inserted last removed first from
the stack.
 A standard queue.
 It is FIFO(First In First Out), i.e., the
Queue <queue> No Iterator
element inserted first removed first from
the queue.
 It is priority queue.
Priority Queue  The element with the highest priority is <queue> No Iterator
removed first from the queue.
Mr. BAPUJI RAO, Dept. of CSE
VECTOR
13

 Vectors are the dynamic arrays with the ability to resize them automatically when
an element is inserted or deleted.

SRM IST, DELHI-NCR CAMPUS


 Insertion and deletion of data takes place at the end.

CONSTRUCTORS PURPOSE
The default vector constructor takes no arguments, creates a
vector( )
new instance of that vector.
It is a default copy constructor that can be used to create a new
vector(const vector& C)
vector that is a copy of the given vector C.
The parameterized constructor creates a vector with space for
vector(size_type num, const TYPE& val = TYPE( )) num objects. If val is specified, each of those objects will be
given that value.
It creates a vector that is initialized to contain the elements
vector(iterator start, iterator end )
between start and end.
Mr. BAPUJI RAO, Dept. of CSE
VECTOR METHODS
14

METHODS PURPOSE
int vector_name.size( ); It returns the number of items in the vector.
void vector_name.push_back(element); It adds an element to the end of the vector.

SRM IST, DELHI-NCR CAMPUS


void vector_name.pop_back( ); It removes the last element of a vector.
It returns an iterator to the beginning of the
vector<data_type>::iterator iterator_name = vector_name.begin( );
vector.
vector<data_type>::iterator iterator_name = vector_name.end( ); It returns an iterator just past the last element
of a vector.

void vector_name.assign( size_type num, const TYPE& val ); It assigns num copies of val to a vector.

void vector_name.assign( iterator start, iterator end ); It copies one vector to another from iterator
start to iterator end.
vector<data_type>::reverse_iterator iterator_name = It returns the reverse iterator to the end of the
vector_name.rbegin( ); vector.
vector<data_type>::reverse_iterator iterator_name = It returns the reverse iterator to the beginning
vector_name.rend( ); of a vector.
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-1
15

#include<vector>
#include<iostream>
using namespace std;

SRM IST, DELHI-NCR CAMPUS


int main()
{
// default constructor
vector<int> v1;
// Parameterized Constructor creates a vector of size 5 and fills the vector with the default value 10
vector<int> v2(5, 10);
// copy constructor
vector<int> v3(v2);
cout<<"\n\n Size of Vector, v1 Created Using Default Constructor = "<<v1.size()<<endl;
cout<<"\n Size of Vector, v2 Created Using Parametrized Constructor = "<<v2.size()<<endl;
cout<<"\n Size of Vector, v3 Created Using Copy Constructor = "<<v3.size()<<endl;
return 0;
}
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-2
16

#include<vector>
cout<<"\n Vector, v1 Elements:\n";
#include<iostream>
using namespace std; for(int i=0; i<v1.size(); i++)
int main() cout<<" "<<v1[i]<<endl;

SRM IST, DELHI-NCR CAMPUS


{
// default constructors cout<<"\n Vector, v2 Elements:\n";
vector<int> v1, v2; for(int i=0; i<v2.size(); i++)
v1.push_back(10);
cout<<" "<<v2[i]<<endl;
v1.push_back(5);
v1.push_back(15);
// pop the last element of Vector, v2
v1.push_back(20);
v2.pop_back();
cout<<endl<<endl;
// store numbers in Vector, v2
cout<<"\n Now Vector, v2 Elements:\n";
for(int i=0, num; i<5; i++)
{ for(int i=0; i<v2.size(); i++)
cout<<" Enter a Number : "; cout<<" "<<v2[i]<<endl;
cin>>num; return 0;
v2.push_back(num);
}
}
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-3
17

#include<vector>
#include<iostream> // copying a vector in another vector
using namespace std; v3.assign(in1,in2);
int main()

SRM IST, DELHI-NCR CAMPUS


{ cout<<"\n Vector, v1 Elements:\n";
// default constructor for(int i=0; i<v1.size(); i++)
vector<int> v1, v2, v3; cout<<" "<<v1[i]<<endl;
v1.push_back(10);
v1.push_back(5); cout<<"\n Vector, v2 Elements:\n";
v1.push_back(15); for(int i=0; i<v2.size(); i++)
v1.push_back(20); cout<<" "<<v2[i]<<endl;
// assigning 4 copies of 10 in the Vector, v2
v2.assign(4, 10); cout<<"\n Vector, v3 Elements:\n";
for(int i=0; i<v3.size(); i++)
// iterator declaration
cout<<" "<<v3[i]<<endl;
vector<int>::iterator in1, in2; return 0;
it1 = v1.begin(); }
it2 = v1.end();
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-4
cout<<"\n Vector, v1 Elements Using Loop Index Method:\n"; 18
for(int i=0; i<v1.size(); i++)
#include<vector> cout<<" "<<v1[i]<<endl;
#include<iostream>
using namespace std; vector<int>::iterator it;
int main( ) cout<<"\n Vector, v1 Elements Using Iterator Forward Accessing Method:\n";

SRM IST, DELHI-NCR CAMPUS


{ for(it=v1.begin(); it!=v1.end(); it++)
// default constructor {
vector<int> v1; cout<<" "<<*it<<endl;
v1.push_back(10); }
v1.push_back(5); vector<int>::reverse_iterator it1;
v1.push_back(15); for(it1= v1.rbegin(); it1!= v1.rend(); it1++)
v1.push_back(20); {
cout<<" "<<*it1<<endl;
}
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


VECTOR METHODS
19

METHODS PURPOSE
It returns a reference to last element of a
vector<Data_Type> ::iterator vector_name.back( );
vector.
It returns a reference to the first element

SRM IST, DELHI-NCR CAMPUS


vector<Data_Type> ::iterator vector_name.front( );
of a vector.
It returns a reference to the element in the
TYPE& vector_name.at( index );
vector at index.
It returns the number of elements that the
size_type vector_name.capacity( )
vector can hold.
void vector_name.clear( ); It deletes all of the elements in the vector.
It returns true if the vector has no
bool vector_name.empty( );
elements, false otherwise.
vector<Data_Type> ::iterator vector_name.erase( iterator loc ); It deletes a single element at location loc.
vector<Data_Type> ::iterator vector_name.erase( iterator start, iterator It delete a range of elements from start to
end ); end in a vector.

Mr. BAPUJI RAO, Dept. of CSE


VECTOR METHODS
20

METHODS PURPOSE
vector<Data_Type> ::iterator vector_name.insert( iterator loc, const TYPE& It inserts val before loc, returning an
val ); iterator to the element inserted.

SRM IST, DELHI-NCR CAMPUS


It inserts num copies of val before
void vector_name.insert( iterator loc, size_type num, const TYPE& val ); loc.
It inserts the elements from start to
void vector_name.insert( iterator loc, input_iterator start, input_iterator end );
end before loc.
void vector_name.reserve( size_type size ); It sets the capacity of the vector to at
least size.
It exchanges the elements of the
void vector_name1.swap(vector_name2); current vector with those of
vector_name2.
It returns the maximum number of
size_type vector_name.max_size( );
elements that the vector can hold.

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE-5
21

#include<vector> cout<<"\n Vector, v1 Elements:\n";


#include<iostream> for(int i=0; i<v1.size(); i++)
using namespace std; cout<<" "<<v1[i]<<endl;
int main( )

SRM IST, DELHI-NCR CAMPUS


{ cout<<"\n Vector, v2 Elements:\n";
// default constructor for(int i=0; i<v2.size(); i++)
vector<int> v1; cout<<" "<<v2[i]<<endl;
v1.push_back(10);
v1.push_back(5); int first = v1.front();
v1.push_back(15); int last = v1.back();
v1.push_back(20);
cout<<"\n First Element of v1 = "<<first<<endl;
vector<int>::iterator it1, it2; cout<<"\n Last Element of V1 = "<<last<<endl;
it1 = v1.begin(); return 0;
it2 = v1.end(); }
vector<int> v2(it1, it2);
vector<int> v2(it1, it2);
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-6
22
// insert() method to splice four copies of the character 'Z' into a vector of 10 characters.
#include<vector>
#include<iostream>
using namespace std;
int main()

SRM IST, DELHI-NCR CAMPUS


{
// Create a vector, load it with the first 10 characters of the alphabet
vector<char> alpha;
for( int i=0; i < 10; i++ )
{
alpha.push_back( i + 65 );
}
vector<char>::iterator iter; // iterator declaration

cout<<"\n The Vector, alpha :\n\n ";


for( iter = alpha.begin(); iter != alpha.end(); iter++ )
{
cout << *iter; // printing vector character
}

Mr. BAPUJI RAO, Dept. of CSE


Continue…
23
// Insert four Z's into the vector 'alpha'
iter = alpha.begin();
alpha.insert( iter, 4, 'Z' );

cout<<"\n\n The Vector, alpha After Inserting 4 Z at the Begin :\n\n ";

SRM IST, DELHI-NCR CAMPUS


for( iter = alpha.begin(); iter != alpha.end(); iter++ )
{
cout << *iter; // printing vector character
}
cout<<endl<<endl;
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE-7
24

// insert() method to append a vector to another vector.


#include<vector>
#include<iostream> cout<<"\n The Vector, v1 :\n\n ";
using namespace std;

SRM IST, DELHI-NCR CAMPUS


for( int i=0; i<5; i++ )
int main() {
{ cout <<v1[i]<<" ";
vector <int> v1, v2; }
for( int i=1; i <=5; i++ )
{ cout<<"\n\n The Vector, v2 :\n\n ";
v1.push_back(i); for( int i=0; i<5; i++ )
} {
cout <<v2[i]<<" ";
for( int i=6; i <=10; i++ ) }
{
v2.push_back(i);
}

Mr. BAPUJI RAO, Dept. of CSE


Continue…
25
v2.insert(v2.end(), v1.begin(), v1.end());

cout<<"\n\n Appending v1 at the end of v2. \n Now, The Vector, v2 :\n\n ";
for( int i=0; i<v2.size(); i++ )
{

SRM IST, DELHI-NCR CAMPUS


cout <<v2[i]<<" ";
}
cout<<endl<<endl;
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


LIST
26

 Lists are sequences of elements stored in a linked list.


 It allows fast insertions and deletions, but slower random access.

SRM IST, DELHI-NCR CAMPUS


CONSTRUCTORS PURPOSE
The default list constructor takes no arguments, creates a new
list( )
instance of that list.
It is a default copy constructor that can be used to create a new
list(const list& C)
list that is a copy of the given list C.
The parameterized constructor creates a list with space for num
list(size_type num, const TYPE& val = TYPE( )) objects. If val is specified, each of those objects will be given
that value.
It creates a list that is initialized to contain the elements
list(iterator start, iterator end )
between start and end.

Mr. BAPUJI RAO, Dept. of CSE


LIST METHODS
27

METHODS PURPOSE
int list_name.size( ); It returns the number of items in the list.
void list_name.push_back(element); It adds an element to the end of the list.

SRM IST, DELHI-NCR CAMPUS


void list_name.push_front(element); It adds an element to the front of the list.
void list_name.pop_back( ); It removes the last element of a list.
void list_name.pop_front( ); It removes the first element of a list.
It returns an iterator to the beginning of the
list<data_type>::iterator iterator_name = list_name.begin( );
list.
list<data_type>::iterator iterator_name = list_name.end( ); It returns an iterator just past the last element
of a list.
list<data_type>::reverse_iterator iterator_name = It returns the reverse iterator to the end of the
list_name.rbegin( ); list.
list<data_type>::reverse_iterator iterator_name = It returns the reverse iterator to the beginning
list_name.rend( ); of a list.

Mr. BAPUJI RAO, Dept. of CSE


LIST METHODS
28

METHODS PURPOSE
list<Data_Type> ::iterator List_Name.back( ); It returns a reference to last element of a list.
list<Data_Type>::iterator List_Name.front( ); It returns a reference to the first element of a list.

SRM IST, DELHI-NCR CAMPUS


void list_name.assign(size_type num, const TYPE& val ); It assigns num copies of val in the list.
void list_name.assign(iterator start, iterator end ); It assigns the values from start to end in the list.
void List_Name.clear( ); It deletes all of the elements in the list.
It returns true if the list has no elements, false
bool List_Name.empty( );
otherwise.
It deletes a single element at location loc in the list.
list<Data_Type> ::iterator List_Name.erase( iterator loc ); The return value is the element after the loc element
erased.
It delete a range of elements from start to end-1 in a
list<Data_Type> ::iterator List_Name.erase( iterator start, list.
iterator end ); The return value is the element after the end-1 element
erased.

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE-1
29

// Demonstration of size().
#include <list>
#include<iostream>

SRM IST, DELHI-NCR CAMPUS


using namespace std;
int main( )
{
list<int> list1, list2(5, 10), list3(list2);

cout<<"\n Size of list1 = "<<list1.size();


cout<<"\n\n Size of list2 = "<<list2.size();
cout<<"\n\n Size of list3 = "<<list3.size();

cout<<endl;
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE-2
30

// Demonstration of push_back() and push_front()


// to store 5 integers from array into two lists and list<int>::iterator it;
// display it.
#include <list> cout<<"\n The List1 Elements:\n";

SRM IST, DELHI-NCR CAMPUS


#include<iostream> for(it=list1.begin(); it!=list1.end(); it++)
#include<iterator> {
using namespace std; cout <<"\n "<<*it;
int main( ) }
{
int arr[] = {10, 20, 30, 40, 50}; cout<<"\n\n The List2 Elements:\n";
list<int> list1, list2; for(it=list2.begin(); it!=list2.end(); it++)
// store array elements in list1 from back of the list {
for(int i=0; i<5; i++) cout <<"\n "<<*it;
list1.push_back(arr[i]); }
cout<<endl;
// store array elements in list2 from front of the list return 0;
for(int i=0; i<5; i++) }
list2.push_front(arr[i]);

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE-3
31
// Demonstration of assign() to store 6 copies
// of the integer 40 into a list and display it.
#include <list>
#include<iostream>
#include<iterator>

SRM IST, DELHI-NCR CAMPUS


using namespace std;
int main()
{
list<int> mylist;
mylist.assign( 6, 40 );
cout<<"\n The List Elements:\n";
list<int>::iterator it;
for(it=mylist.begin(); it!=mylist.end(); it++)
{
cout <<"\n "<<*it;
}
cout<<endl;
return 0;
}
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-4
32
// Demonstration of merging of two lists
#include <list>
#include<iostream>
#include<iterator>
using namespace std;

SRM IST, DELHI-NCR CAMPUS


int main( )
{
int arr1[] = {10, 20, 30, 40}, arr2[]={1 ,2, 3, 4}, arr3[]={9, 5, 11, 7, 15};
list<int> list1, list2, list3;

// store arr1 elements in list1 from back of the list


for(int i=0; i<4; i++)
{
list1.push_back(arr1[i]);
}

// store arr2 elements in list2 from back of the list


for(int i=0; i<4; i++)
{
list2.push_back(arr2[i]);
}
Mr. BAPUJI RAO, Dept. of CSE
Continue…
// store arr3 elements in list3 from back of the list 33
for(int i=0; i<5; i++)
{
list3.push_back(arr3[i]);
}
list<int> list4(list2);

SRM IST, DELHI-NCR CAMPUS


list<int>::iterator it;
cout<<"\n The List1 Elements:";
for(it=list1.begin(); it!=list1.end(); it++)
{
cout <<"\n "<<*it;
}
cout<<"\n\n The List2 Elements:";
for(it=list2.begin(); it!=list2.end(); it++)
{
cout <<"\n "<<*it;
}
cout<<"\n\n The List3 Elements:";
for(it=list3.begin(); it!=list3.end(); it++)
{
cout <<"\n "<<*it;
} Mr. BAPUJI RAO, Dept. of CSE
Continue…
34

cout<<"\n\n The List4 Elements:";


for(it=list4.begin(); it!=list4.end(); it++)
{
cout <<"\n "<<*it;

SRM IST, DELHI-NCR CAMPUS


}
list2.merge(list1);
list4.merge(list3);
cout<<"\n\n The List2 Elements After Merging with List1:";
for(it=list2.begin(); it!=list2.end(); it++)
{
cout <<"\n "<<*it;
}
cout<<"\n\n The List4 Elements After Merging with List3:";
for(it=list4.begin(); it!=list4.end(); it++)
{
cout <<"\n "<<*it;
}
cout<<endl;
return 0;
} Mr. BAPUJI RAO, Dept. of CSE
DEQUE
35

 It allows fast insertions and deletions at the beginning as well as


the end of the container.

SRM IST, DELHI-NCR CAMPUS


CONSTRUCTORS PURPOSE
The default deque constructor takes no arguments, creates a
deque( )
new instance of that deque.
It is a default copy constructor that can be used to create a new
deque(const deque& C)
deque that is a copy of the given deque C.
The parameterized constructor creates a deque with space for
deque(size_type num, const TYPE& val = TYPE( )) num objects. If val is specified, each of those objects will be
given that value.
It creates a deque that is initialized to contain the elements
deque(iterator start, iterator end )
between start and end.

Mr. BAPUJI RAO, Dept. of CSE


DEQUE METHODS
36

METHODS PURPOSE
int deque_name.size( ); It returns the number of items in the deque.
void deque_name.push_back(element); It adds an element to the end of the deque.

SRM IST, DELHI-NCR CAMPUS


void deque_name.push_front(element); It adds an element to the front of the deque.
void deque_name.pop_back( ); It removes the last element of a deque.
void deque_name.pop_front( ); It removes the first element of a deque.
It returns an iterator to the beginning of the
deque<data_type>::iterator iterator_name = deque_name.begin( );
deque.
deque<data_type>::iterator iterator_name = deque_name.end( ); It returns an iterator just past the last element
of a deque.
deque<data_type>::reverse_iterator iterator_name = It returns the reverse iterator to the end of the
deque_name.rbegin( ); deque.
deque<data_type>::reverse_iterator iterator_name = It returns the reverse iterator to the beginning
deque_name.rend( ); of a deque.

Mr. BAPUJI RAO, Dept. of CSE


DEQUE METHODS
37

METHODS PURPOSE
deque<Data_Type> ::iterator deque_name.back( ); It returns a reference to last element of a deque.
deque<Data_Type>::iterator deque_name.front( ); It returns a reference to the first element of a deque.

SRM IST, DELHI-NCR CAMPUS


void deque_name.assign(size_type num, const TYPE& val ); It assigns num copies of val in the deque.
void deque_name.assign(iterator start, iterator end ); It assigns the values from start to end in the deque.
void deque_name.clear( ); It deletes all of the elements in the deque.
It returns true if the list has no elements, false
bool deque_name.empty( );
otherwise.
It deletes a single element at location loc in the
deque.
deque<Data_Type> ::iterator deque_name.erase( iterator loc );
The return value is the element after the loc element
erased.
It delete a range of elements from start to end-1 in
deque<Data_Type> ::iterator deque_name.erase( iterator start, a deque.
iterator end ); The return value is the element after the end-1
element erased.
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-1
38

// Demonstration of deque constructors and size( ).


#include <deque>
#include<iostream>

SRM IST, DELHI-NCR CAMPUS


using namespace std;
int main( )
{
deque<int> dq1, dq2(5, 10), dq3(dq2);

cout<<"\n Size of Deque-1 = "<<dq1.size();


cout<<"\n\n Size of Deque-2 = "<<dq2.size();
cout<<"\n\n Size of Deque-3 = "<<dq3.size();
cout<<endl;
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE-2
39

// Demonstration of assign() to store 6 copies of the integer 40 into a deque and display it.
#include <deque>
#include<iostream>
#include<iterator>

SRM IST, DELHI-NCR CAMPUS


using namespace std;
int main()
{
deque<int> dq;
dq.assign( 6, 40 );

cout<<"\n The Deque Elements:\n";


deque<int>::iterator it;
for(it=dq.begin(); it!=dq.end(); it++)
{
cout <<"\n "<<*it;
}
cout<<endl;
return 0;
}
Mr. BAPUJI RAO, Dept. of CSE
EXAMPLE-3
40

// Demonstration of push_back() and push_front()


// to store 5 integers from array into two deques and
// display it. cout<<"\n The Deque-1 Elements:\n";
#include <deque> for(it=dq1.begin(); it!=dq1.end(); it++)

SRM IST, DELHI-NCR CAMPUS


#include<iostream> {
#include<iterator> cout <<"\n "<<*it;
using namespace std; }
int main( )
{ cout<<"\n\n The Deque-2 Elements:\n";
int arr[] = {10, 20, 30, 40, 50}; for(it=dq2.begin(); it!=dq2.end(); it++)
deque<int> dq1, dq2; {
// store array elements in dq1 from back of the deque cout <<"\n "<<*it;
for(int i=0; i<5; i++) }
dq1.push_back(arr[i]); cout<<endl;
return 0;
// store array elements in dq2 from front of the deque }
for(int i=0; i<5; i++)
dq2.push_front(arr[i]);
deque<int>::iterator it;
Mr. BAPUJI RAO, Dept. of CSE
ASSOCIATIVE CONTAINERS
41

 In an associative container the items are not arranged in sequence.


 they are arranged in a more complex way that makes it much faster to find a given item.
 The arrangement is typically a tree structure.

SRM IST, DELHI-NCR CAMPUS


 The two main categories of associative containers in the STL are sets and maps.
 Set: A set stores objects containing keys.
 Map: A map stores pairs, where the first part of the pair is an object containing a key and the second
part is an object containing a value.
 In both a set and a map, only one example of each key can be stored.
 A multiset and a multimap are similar to a set and a map, but can include multiple instances of the
same key.
 some algorithms, such as lower_bound( ) and equal_range( ), exist only for associative containers.

Mr. BAPUJI RAO, Dept. of CSE


SET CONSTRUCTORS
42

CONSTRUCTORS PURPOSE
The default set constructor takes no arguments, creates a new instance of that
set( )

SRM IST, DELHI-NCR CAMPUS


set.
The parameterized constructor creates a set with space for size elements of
set(array_name, array_name + size)
array_name.
set(old_set_name) It creates a set by coping the contents of old_set_name in the newly created set.
It creates a set that is initialized to contain the elements between start and end
set(iterator start, iterator end )
of the iterable container.

Mr. BAPUJI RAO, Dept. of CSE


SET METHODS
43

METHODS PURPOSE
begin It returns an iterator to the beginning of the set.

SRM IST, DELHI-NCR CAMPUS


clear It removes all elements from the set.
count It returns the number of elements matching a certain key.
empty It returns a true if the set has no elements.
erase It removes elements from a set.
find It returns an iterator to specific elements.
insert It inserts items into a set.
rbegin It returns a reverse_iterator to the end of the set.
rend It returns a reverse_iterator to the beginning of the set.
size It returns the number of items in the set.
lower_bound It returns an iterator to the first element greater than or equal to a certain value.
upper_bound It returns an iterator to the first element greater than a certain value.

Mr. BAPUJI RAO, Dept. of CSE


SET EXAMPLE-1
44

// Demonstration of set constructors and size() method. cout<<"\n Size of set1 = "<<set1.size();
#include <iostream> cout<<"\n\n Size of set2 = "<<set2.size();
#include <vector> cout<<"\n\n Size of set3 = "<<set3.size();
#include <set>

SRM IST, DELHI-NCR CAMPUS


#include <iterator> cout<<"\n\n Items of set2 = ";
using namespace std; for(it=set2.begin(); it!=set2.end(); it++)
int main() cout<<" "<<*it;
{
int arr[]={10,6,9,5,2}; cout<<"\n\n Items of set3 = ";
vector<int> v; for(it=set3.begin(); it!=set3.end(); it++)
for(int i=4; i>=0; i--) cout<<" "<<*it;
v.push_back(arr[i]); cout<<endl;
return 0;
//declare set object }
set<int> set1, set2(arr, arr+5), set3(v.begin(), v.end());
// set iterator
set<int>::iterator it;

Mr. BAPUJI RAO, Dept. of CSE


SET EXAMPLE-2
45

// set to store integer objects.


#include <iostream> //display size of set
#include <set> cout<<"\n\n Size of numberSet = "<<numberSet.size()<<endl;
#include <string> cout<<"\n The Numbers From The Set:";

SRM IST, DELHI-NCR CAMPUS


#include<iterator> for(iter = numberSet.begin();iter != numberSet.end(); iter++)
using namespace std; cout <<"\n "<<*iter;
int main() cout<<endl;
{ return 0;
int num; }
//declare set object
set<int, less<int> > numberSet;
//iterator to set
set<int, less<int> >::iterator iter;
for(int i=1; i<=6; i++)
{
cout<<"\n Enter Number-"<<i<<" : " ;
cin>>num;
numberSet.insert(num);
} Mr. BAPUJI RAO, Dept. of CSE
SET EXAMPLE-3
46

 Syntax-1:
set<Data_Type, less<Data_Type> > Set_Name(Array_Name, Array_Name + Array_Size);

SRM IST, DELHI-NCR CAMPUS


// set to store string objects and search a name from the set.
#include <iostream>
#include <set>
#include <string> //initialize array to set
#include<iterator> set<string, less<string> > nameSet(names, names+5);
using namespace std; //iterator to set
int main( ) set<string, less<string> >::iterator iter;
{ nameSet.insert("Yuvaraj"); //insert more names
//array of string objects nameSet.insert("Kiran");
string names[ ]={"Juli", "Robin", "Manu", "Aman", "Mani"}; nameSet.insert("Robin"); //no effect; already in set
nameSet.insert("Balu");
cout<<"\n The Names From The Array :\n ";
for(int i=0; i<5; i++)
cout<<"\n "<<names[i];
Mr. BAPUJI RAO, Dept. of CSE
Continue…
47

//display size of set //find matching name in set


cout <<"\n\n Size of nameSet = " << nameSet.size() << endl; iter = nameSet.find(searchName);
if( iter == nameSet.end() )
cout <<"\n The Names From The Set:"; cout <<"\n The name " <<searchName <<" is NOT in the Set.";

SRM IST, DELHI-NCR CAMPUS


for(iter = nameSet.begin();iter != nameSet.end(); iter++) else cout << "\n The name " << *iter << " is in the Set.";
cout <<"\n "<<*iter; cout << endl;
return 0;
nameSet.erase("Balu"); //erase a name }
nameSet.erase("Robin"); //erase a name

//display size of set


cout <<"\n\n Size of nameSet = "<< nameSet.size()<< endl;

cout <<"\n The Names From The Set After Deletion of 'Balu' And 'Robin':";
for(iter = nameSet.begin();iter != nameSet.end(); iter++)
cout <<"\n "<<*iter;

string searchName; //get name from user


cout << "\n\n Enter name to search for: ";
cin >> searchName;
SET EXAMPLE-4
48

// set to store integer objects and display


// it using lower_bound() and upper_bound() methods.
#include <iostream> for(int i=1; i<=n; i++)
#include <set> {

SRM IST, DELHI-NCR CAMPUS


#include <string> cout<<"\n Enter Number-"<<i<<" : " ;
#include<iterator> cin>>num;
using namespace std; numberSet.insert(num);
int main( ) }
{ //display size of set
int num, n, lower, upper; cout <<"\n\n Size of numberSet = " << numberSet.size() << endl;
//declare set object
set<int, less<int> > numberSet; cout <<"\n The Numbers From The Set:";
//iterator to set for(iter = numberSet.begin(); iter!= numberSet.end(); iter++)
set<int, less<int> >::iterator iter; cout <<"\n "<<*iter;
cout<<"\n How Many Integers to be Stored in the Set ? ";
cin>>n;

Mr. BAPUJI RAO, Dept. of CSE


Continue…
49

cout<<"\n Enter the Lower Bound of Set: ";

SRM IST, DELHI-NCR CAMPUS


cin>>lower;
cout<<"\n Enter the Upper Bound of Set: ";
cin>>upper;

cout <<"\n The Numbers From Lower Bound-"<<lower<<" To Upper Bound-"<<upper;


for(iter = numberSet.lower_bound(lower);iter != numberSet.upper_bound(upper); iter++)
cout <<"\n "<<*iter;

cout<<endl;
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


MULTISET EXAMPLE
50

// Demonstration of multiset constructors and //declaration of set iterator


// size() method. set<int>::iterator it;
#include <iostream> cout<<"\n\n Items of set1 = ";
#include <vector> for(it=set1.begin(); it!=set1.end(); it++)

SRM IST, DELHI-NCR CAMPUS


#include <set> cout<<" "<<*it;
#include <iterator>
using namespace std; //declaration of multiset iterator
int main() multiset<int>::iterator mit;
{ cout<<"\n\n Items of multiset set2 = ";
int arr[]={10,5,6,9,5,2,9}; for(mit=set2.begin(); mit!=set2.end(); mit++)
cout<<" "<<*mit;
//declaration of set object cout<<endl;
set<int> set1(arr, arr+7); return 0;
}
//declaration of multiset object
multiset<int> set2(arr, arr+7);

cout<<"\n Size of set1 = "<<set1.size();


cout<<"\n\n Size of multiset set2 = "<<set2.size();
Mr. BAPUJI RAO, Dept. of CSE
MAP EXAMPLE-1
51

 Syntax: map<string, string/int/float less<string> > Map_Name;

#include <iostream>

SRM IST, DELHI-NCR CAMPUS


#include <string>
#include <map>
#include<iterator>
using namespace std;
int main( )
{
string name, cap;
string states[ ] = { "Odisha", "AP", "UP", "MP", "Bihar"};
string capitals[ ] = {"Bhubaneswar", "Hyderabad","Lucknow", "Bhopal", "Patna" };

map<string, string, less<string> > mapStates; //map object declaration

map<string, string, less<string> >::iterator iter; // map iterator declaration

Mr. BAPUJI RAO, Dept. of CSE


Continue…
52

for(int i=0; i<5; i++)


{
//get data from arrays

SRM IST, DELHI-NCR CAMPUS


name = states[i];
cap = capitals[i];
//put it in map
mapStates[name] = cap;
}
cout<<"\n States\t\tCapitals\n";
cout<<" ------\t\t-------\n";
for(iter = mapStates.begin(); iter != mapStates.end(); iter++)
cout <<" "<<(*iter).first <<"\t\t" << (*iter).second <<endl ;

cout<<endl;
return 0;
}
Mr. BAPUJI RAO, Dept. of CSE
MAP EXAMPLE-2
53

#include<iostream> int main()


#include<map> {
#include<iterator> map<const char*, int> ages;
#include<string.h> // store key:value pairs in the map

SRM IST, DELHI-NCR CAMPUS


using namespace std; ages["Hari"] = 38;
struct strCmp ages["Mani"] = 21;
{ ages["Bitu"] = 17;
bool operator()( const char* s1, const char* s2 ) const ages["Neelu"] = 29;
{ ages["Bhanu"] = 11;
return strcmp( s1, s2 ) < 0; map<const char*, int, strCmp> ages1;
} // store key:value pairs in the map
}; ages1["Hari"] = 38;
ages1["Mani"] = 21;
ages1["Bitu"] = 17;
ages1["Neelu"] = 29;
ages1["Bhanu"] = 11;

cout << "\n Bhanu is " << ages["Bhanu"] << " years old" << endl;

Mr. BAPUJI RAO, Dept. of CSE


Continue…
54

cout << "\n\n The First Map in Original Order: " << endl<<endl;

map<const char*, int>::iterator iter;

SRM IST, DELHI-NCR CAMPUS


for(iter= ages.begin(); iter !=ages.end(); iter++ )
{
cout <<" "<< (*iter).first << " is " << (*iter).second << " years old" << endl;
}
cout << "\n\n The Second Map in Alphabetical order: " << endl<<endl;

map<const char*, int, strCmp>::iterator iter1;

for(iter= ages1.begin(); iter !=ages1.end(); iter++ )


{
cout <<" "<< (*iter).first << " is " << (*iter).second << " years old" << endl;
}
cout<<endl;
return 0;
}
Mr. BAPUJI RAO, Dept. of CSE
MAP EXAMPLE-3
55

 insert( ) Method Syntax:


Map_Name.insert(pair<data_type, data_type>(key, value));

SRM IST, DELHI-NCR CAMPUS


// insert() method to store key:value pair in a map
#include <iostream>
#include <string>
#include <map>
#include<iterator>
using namespace std;
int main()
{
string name, cap;
string states[] = { "Odisha", "AP", "UP", "MP", "Bihar"};
string capitals[] = {"Bhubaneswar", "Hyderabad","Lucknow", "Bhopal", "Patna" };
map<string, string> mapStates; //map
map<string, string>::iterator iter; //iterator
Mr. BAPUJI RAO, Dept. of CSE
Continue…
56

for(int i=0; i<5; i++)


{
name = states[i]; //get data from arrays
cap = capitals[i];

SRM IST, DELHI-NCR CAMPUS


mapStates.insert(pair<string, string>(name, cap)); //put it in map
//mapStates[name] = cap; //put it in map
}

cout<<"\n States\t\tCapitals\n";
cout<<" ------\t\t-------\n";
for(iter = mapStates.begin(); iter != mapStates.end(); iter++)
cout <<" "<<iter->first <<"\t\t" <<iter->second <<endl ;
//cout <<" "<<(*iter).first <<"\t\t" <<(*iter).second <<endl ;

cout<<endl;
return 0;
}
Mr. BAPUJI RAO, Dept. of CSE
MULTIMAP EXAMPLE-1
57

// demonstration of multimap program


#include <iostream>
#include <iterator>
#include <map>

SRM IST, DELHI-NCR CAMPUS


using namespace std;
for (itr = mmap1.begin(); itr != mmap1.end(); ++itr)
int main( )
{
{
cout << ' ' << itr->first << '\t' << itr->second << '\n';
// empty multimap container
}
multimap<int, int> mmap1;
cout << endl;
// insert elements in random order
mmap1.insert(pair<int, int>(1, 40));
// adding elements randomly, to check the sorted keys property
mmap1.insert(pair<int, int>(3, 30));
mmap1.insert(pair<int, int>(4, 50));
mmap1.insert(pair<int, int>(2, 60));
mmap1.insert(pair<int, int>(7, 10));
mmap1.insert(pair<int, int>(6, 70));
mmap1.insert(pair<int, int>(6, 20));
// printing multimap mmap1
multimap<int, int>::iterator itr;
cout << "\n The multimap mmap1: \n";
cout << " KEY\tELEMENT\n"; Mr. BAPUJI RAO, Dept. of CSE
Continue…
58

// printing multimap mmap1 again


cout << "\n The multimap mmap1 after adding extra elements : \n";
cout << " KEY\tELEMENT\n";
for (itr = mmap1.begin(); itr != mmap1.end(); ++itr)

SRM IST, DELHI-NCR CAMPUS


cout << ' ' << itr->first << '\t' << itr->second << '\n';

cout << endl;


// second multimap mmap2 creation and filling mmap1 key:value pairs
multimap<int, int> mmap2(mmap1.begin(), mmap1.end());
// print all elements of the multimap mmap2
cout << "\n The multimap mmap2 after assign from mmap1 : \n";
cout << " KEY\tELEMENT\n";
for (itr = mmap2.begin(); itr != mmap2.end(); ++itr)
cout << ' ' << itr->first << '\t' << itr->second << '\n';

cout << endl;


return 0;
}
Mr. BAPUJI RAO, Dept. of CSE
MULTIMAP EXAMPLE-2
59

// demonstration of multimap program with


// lower_bound(), upper_bound(), and erase() Methods
#include <iostream>
#include <iterator>

SRM IST, DELHI-NCR CAMPUS


#include <map> // printing multimap mmap1
using namespace std; multimap<int, int>::iterator itr;
int main( )
{ cout << "\n The multimap mmap1: \n";
// empty multimap container cout << " KEY\tELEMENT\n";
multimap<int, int> mmap1; for (itr = mmap1.begin(); itr != mmap1.end(); ++itr)
// insert elements in random order {
mmap1.insert(pair<int, int>(1, 40)); cout << ' ' << itr->first << '\t' << itr->second<< '\n';
mmap1.insert(pair<int, int>(3, 30)); }
mmap1.insert(pair<int, int>(2, 60)); cout << endl;
mmap1.insert(pair<int, int>(6, 70));
mmap1.insert(pair<int, int>(6, 20));
mmap1.insert(pair<int, int>(4, 50));
mmap1.insert(pair<int, int>(7, 10)); Mr. BAPUJI RAO, Dept. of CSE
Continue…
60

// remove all elements with key = 6


int num;
num = mmap1.erase(6);
cout << "\n mmap1.erase(6) : ";
cout << num << " removed \n";

SRM IST, DELHI-NCR CAMPUS


cout << "\n The multimap mmap1 after removal of key = 6 :\n";
cout << " KEY\tELEMENT\n";
for (itr = mmap1.begin(); itr != mmap1.end(); ++itr)
{
cout << ' ' << itr->first << '\t' << itr->second<< '\n';
}
cout << endl;
// lower bound and upper bound for multimap mmap1 key = 6
cout << "\n mmap1.lower_bound(3) : "<< "\tKEY = ";
cout << mmap1.lower_bound(3)->first << '\t';
cout << "\tELEMENT = " << mmap1.lower_bound(3)->second<< endl;
cout << "\n\n mmap1.upper_bound(3) : "<< "\tKEY = ";
cout << mmap1.upper_bound(3)->first << '\t';
cout << "\tELEMENT = " << mmap1.upper_bound(3)->second<< endl;
return 0;
} Mr. BAPUJI RAO, Dept. of CSE
STACK
61

 It is a container adapter that gives the programmer the functionality of a stack - a FILO (first-
in, last-out) or LIFO(last-in, first-out) data structure.

METHODS PURPOSE

SRM IST, DELHI-NCR CAMPUS


empty( ) It returns true if the stack has no elements.

pop( ) It removes the top element of a stack.

push( ) It adds or pushes an element to the top of the stack.

size( ) It returns the number of items in the stack.

top( ) It returns the top element of the stack.

Mr. BAPUJI RAO, Dept. of CSE


STACK EXAMPLE
62

// Demostration of stack program cout<<"\n The Stack Elements After Popping Out Three Elements:\n";
#include<iostream> while (!s.empty())
#include<stack> {
using namespace std; cout <<" "<< s.top() <<"\n";

SRM IST, DELHI-NCR CAMPUS


int main( ) s.pop();
{ }
stack<int> s;
s.push(21); return 0;
s.push(2); }
s.push(24);
s.push(15);
int num=6;
s.push(num);
// pop three elements from the stack
s.pop();
s.pop();
s.pop();
Mr. BAPUJI RAO, Dept. of CSE
find( ) ALGORITHM
63

 It searches for a particular element in a container.


 If the element is found successfully in the container, then it will return its address.

SRM IST, DELHI-NCR CAMPUS


 If it is not found, then it will return the last address of the container.
 Syntax:
Data_Type *Pointer = find(Container_Begin_Address, Container_End_Address, element);

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE
// To find the first object with a specified value 64
#include <iostream>
#include <algorithm> //for find( )
using namespace std; 1st RUN
int arr[] = { 10, 40, 30, 40, 50, 30, 60, 70 };
int main()

SRM IST, DELHI-NCR CAMPUS


{
int *ptr, num;
cout<<"\n The Array Numbers...\n\n ";
for(int i=0; i<8; i++)
cout<<arr[i]<<" ";
cout<<"\n\n Enter a Number to find in the above Array:"; 2nd RUN
cin>>num;
ptr = find(arr, arr+8, num); //find first num

if(ptr==arr+8)
cout<<endl<<" "<<num<<" Not Found\n\n";
else
cout<<"\n First "<<num<<" found at Index=" <<(ptr-arr)<<endl<<endl;
return 0;
} Mr. BAPUJI RAO, Dept. of CSE
count( ) ALGORITHM
65

 It counts number of objects with the specified value in a container.


 Syntax:
int variable = count(Container_Begin_Address, Container_End_Address, Element);

SRM IST, DELHI-NCR CAMPUS


#include <iostream>
#include <algorithm> //for count()
using namespace std;
int arr[] = { 30, 20, 30, 40, 30, 50, 60, 70 };
int main( )
{
int n = count(arr, arr+8, 30); //count number of 30's
cout<<"\n\n The Array Numbers are:\n";
for(int i=0; i<8; i++)
cout<<" "<<arr[i];
cout<<"\n\n There are "<<n<<" 30's in the above Array"<<endl;
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


sort( ) ALGORITHM
66

 It sorts a container in ascending and descending order.


 Syntax for Ascending Order:

SRM IST, DELHI-NCR CAMPUS


sort(Container_Begin_Address, Container_End_Address);
 Syntax for Descending Order:
sort(Container_Begin_Address, Container_End_Address, greater<Data_Type>( ));

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE
67

#include<iostream>
#include <algorithm> cout<<"\n\n The Ascending Sorted Array arr1:\n";
#include<functional> // for greater<>( ) for(int i=0; i<8; i++)
using namespace std; cout<<' '<<arr1[i];

SRM IST, DELHI-NCR CAMPUS


//array of numbers cout<<endl;
int arr1[ ] = {4, 2, 22, 1, 0, 3, 25, 5};
int arr2[ ] = {4, 2, 22, 1, 0, 3, 25, 5}; cout<<"\n\n The Descending Sorted Array arr2:\n";
int main( ) for(int i=0; i<8; i++)
{ cout<<' '<<arr2[i];
//sort the numbers of arr1 in ascending order cout<<endl;
sort(arr1, arr1+8); return 0;
//sort the numbers of arr2 in descending order }
sort(arr2, arr2+8, greater<int>());

Mr. BAPUJI RAO, Dept. of CSE


search( ) ALGORITHM
68

 It searches for a container in a given container.


 Syntax:
Data_type *pointer = search(Container1_Begin_Address, Container1_End_Address,
Container2_Begin_Address, Container2_End_Address)

SRM IST, DELHI-NCR CAMPUS


#include <iostream>
#include <algorithm>
using namespace std;
int array[] = { 11, 44, 33, 11, 22, 33, 11, 22, 44 };
int sub_array[] = { 11, 22, 33 };
int main()
{
int* ptr;
ptr = search(array, array+9, sub_array, sub_array+3);
if(ptr == array+9) //if past-the-end
cout <<"\n No match found\n";
else
cout <<"\n\n Match at "<<(ptr - array)<<endl;
return 0;
} Mr. BAPUJI RAO, Dept. of CSE
merge( ) ALGORITHM
 It merges two containers and stores the result in a new container. 69

 Syntax:
merge(Container1_Begin_Address, Container1_End_Address,
Container2_Begin_Address, Container2_End_Address, Resultant_Container)

SRM IST, DELHI-NCR CAMPUS


#include <iostream>
#include <algorithm> //for merge()
using namespace std;
int arr1[] = { 2, 3, 4, 6, 8 };
int arr2[] = { 1, 3, 5 };
int result[8];
int main()
{
//merge arr1 and arr2 and store in result
merge(arr1, arr1+5, arr2, arr2+3, result);
cout<<"\n\n The Merged Array Elements are:\n\n";
for(int i=0; i<8; i++)
cout <<" "<<result[i];
cout << endl;
return 0;
} Mr. BAPUJI RAO, Dept. of CSE
for_each( ) ALGORITHM
70

 Syntax:
for_each(Container_Begin_Address, Container_End_Address, Function_For_Result);

SRM IST, DELHI-NCR CAMPUS


#include <iostream> cout<<"\n Inches:\n";
#include <algorithm> for(int i=0; i<5; i++)
using namespace std; cout<<"\n "<<inches[i];
//convert and display as centimetres
void in_to_cm(double in) cout<<endl;
{
cout <<"\n "<<(in * 2.54); cout<<"\n Centimeters:\n";
} for_each(inches, inches+5, in_to_cm);
int main()
{ cout << endl;
//array of inches values return 0;
double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; }
Mr. BAPUJI RAO, Dept. of CSE
transform( ) ALGORITHM
71

 It changes the container items and stores in the same container or different container.
 Syntax:
tranform(Container_Begin_Address, Container_End_Address, New_Container,

SRM IST, DELHI-NCR CAMPUS


Function_To_Store_In_New_Container);

#include <iostream> //transform into array centi[]


#include <algorithm> transform(inches, inches+5, centi, in_to_cm);
using namespace std;
//convert inches to centimetres cout<<"\n\n The Array Numbers in Inches:\n";
double in_to_cm(double in) for(int i=0; i<5; i++)
{ cout <<" "<<inches[i];
return (in * 2.54); //return result
} cout<<"\n\n The Array Numbers in Centimetres:\n";
int main() for(int i=0; i<5; i++)
{ cout <<" "<<centi[i];
//array of inches values
double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; cout << endl;
double centi[5]; return 0;
double in_to_cm(double); //prototype }
Mr. BAPUJI RAO, Dept. of CSE
SPECIALIZED ITERATORS
72

ITERATOR ADAPTERS STREAM ITERATORS


 It provides three variations on the  It uses files and I/O (cin and cout) devices

SRM IST, DELHI-NCR CAMPUS


normal iterator. as arguments to algorithms.
 Input and output iterators make it possible
for appropriate algorithms to be used
directly on input and output streams.

REVERSE INSERT
ITERATOR ITERATOR ostream_iterator istream_iterator

RAW STORAGE
ITERATOR

Mr. BAPUJI RAO, Dept. of CSE


REVERSE ITERATOR EXAMPLE
73

#include <iostream> list<int>::reverse_iterator revit;


#include <list> cout<<"\n\n The Reverse List:\n";
using namespace std; for(revit = mylist.rbegin(); revit != mylist.rend(); revit++)

SRM IST, DELHI-NCR CAMPUS


int main() cout <<' '<<*revit; //displaying output
{ cout << endl;
int arr[] = { 2, 4, 6, 8, 10 }; //array of integers return 0;
list<int> mylist; }
for(int i=0; i<5; i++) //transfer array
mylist.push_back( arr[i] ); //to list

list<int>::iterator iter;
cout<<"\n The List:\n";
for(iter=mylist.begin(); iter!=mylist.end(); iter++)
cout<<' '<<*iter; //displaying output

Mr. BAPUJI RAO, Dept. of CSE


INSERT ITERATOR EXAMPLE
//demonstrates insert iterators with queues 74
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
 There are three flavors of the insert iterator: int main( )

SRM IST, DELHI-NCR CAMPUS


• back_inserter inserts new items at the {
int arr1[] = { 1, 3, 5, 7, 9 };
end. int arr2[] = { 2, 4, 6, 8, 10 };
• front_inserter inserts new items at the int arr3[] = {20, 30, 40, 50, 60};
deque<int> dq1;
beginning. deque<int> dq2;
• inserter inserts new items at a specified deque<int> dq3;
for(int i=0; i<5; i++) //transfer arrays to deques
location. {
dq1.push_back( arr1[i] );
dq2.push_back( arr2[i] );
dq3.push_back( arr3[i] );
}
Mr. BAPUJI RAO, Dept. of CSE
INSERT ITERATOR EXAMPLE
75

cout<<"\n The First Queue:\n"; //copy dq1 to dq2


for(int i=0; i<dq1.size(); i++) copy( dq1.begin(), dq1.end(), back_inserter(dq2));
cout<<' '<<dq1[i]; cout<<"\n The Second Queue After Insertion of First Queue At The End:\n";
for(int i=0; i<dq2.size(); i++) //display dq2

SRM IST, DELHI-NCR CAMPUS


cout<<"\n The Second Queue:\n"; cout <<' '<<dq2[i];
for(int i=0; i<dq2.size(); i++)
cout<<' '<<dq2[i]; //copy dq1 to dq3
copy( dq1.rbegin(), dq1.rend(), front_inserter(dq3));
cout<<"\n The Third Queue:\n"; cout<<"\n The Third Queue After Insertion of First Queue At The Begin:\n";
for(int i=0; i<dq3.size(); i++) for(int i=0; i<dq3.size(); i++) //display dq2
cout<<' '<<dq3[i]; cout <<' '<<dq3[i];
cout << endl;
return 0;
}

Mr. BAPUJI RAO, Dept. of CSE


ostream_iterator CLASS
76

 The ostream_iterator object can be used as an argument to any algorithm that specifies an output iterator.
 Syntax:
ostream_iterator<Data_Type> Output_Iterator_Name(cout, "Separator Character");

SRM IST, DELHI-NCR CAMPUS


copy(begin_iterator, end_iterator, Output_Iterator_Name)
 Exanples:
ostream_iterator<int> cout_iterator1(cout, " ");
ostream_iterator<int> cout_iterator2(cout, " , ");
copy(mylist.begin(), mylist.end(), cout_iterator1);
copy(mylist.begin(), mylist.end(), cout_iterator2);

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE
77

//demonstrates ostream_iterator //ostream iterators


#include <iostream> ostream_iterator<int> cout_iterator(cout, " ");
#include <algorithm> ostream_iterator<int> cout_iterator1(cout, ", ");
#include <list>

SRM IST, DELHI-NCR CAMPUS


#include<iterator> cout << "\n Contents of List With Space As A Separator: \n ";
using namespace std; copy(mylist.begin(), mylist.end(), cout_iterator); //display list
int main( )
{ cout << "\n\n Contents of List With Comma As A Separator: \n ";
int arr[] = { 10, 20, 30, 40, 50 }; copy(mylist.begin(), mylist.end(), cout_iterator1);
cout << endl;
list<int> mylist; return 0;
}
for(int i=0; i<5; i++) //transfer array to list
mylist.push_back( arr[i] );

Mr. BAPUJI RAO, Dept. of CSE


istream_iterator CLASS
78

 The istream_iterator object can be used as an argument to any algorithm that specifies an input iterator.
 Syntax:
istream_iterator<Data_Type> Input_Iterator_Name(cin);

SRM IST, DELHI-NCR CAMPUS


istream_iterator<Data_Type> end_of_stream;
copy(Input_Iterator_Name, end_of_stream, List_Name.begin( ));
 Exanples:
list<float> mylist(5);
istream_iterator<float> input_iterator(cin);
istream_iterator<float> end_of_stream;
copy(input_iterator, end_of_stream, mylist.begin( ));

Mr. BAPUJI RAO, Dept. of CSE


EXAMPLE
79

// demonstrates istream_iterator //copy from cin to mylist


#include <iostream> copy( cin_iter, end_of_stream, mylist.begin() );
#include <list> cout << endl;
#include <algorithm>

SRM IST, DELHI-NCR CAMPUS


#include<iterator> //display mylist
using namespace std; ostream_iterator<float> ositer(cout, "\n ");
int main( ) cout<<"\n\n The Numbers from the List:\n ";
{ copy(mylist.begin(), mylist.end(), ositer);
list<float> mylist(5); //uninitialized list cout << endl;
return 0;
cout << "\n Enter 5 floating-point numbers: "; }
//istream iterators
istream_iterator<float> cin_iter(cin); //cin
istream_iterator<float> end_of_stream; // ctrl + z

Mr. BAPUJI RAO, Dept. of CSE


SRM IST, DELHI-NCR CAMPUS
80

THANK YOU

You might also like