0% found this document useful (0 votes)
2 views

C++_Programming_Unit-5[1]

The document provides an overview of the Standard Template Library (STL) in C++, detailing its key components: containers, algorithms, and iterators. It categorizes containers into sequence and associative types, and explains various algorithms and iterator types used for data manipulation. Additionally, it includes examples of using vectors and lists, demonstrating their constructors and methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C++_Programming_Unit-5[1]

The document provides an overview of the Standard Template Library (STL) in C++, detailing its key components: containers, algorithms, and iterators. It categorizes containers into sequence and associative types, and explains various algorithms and iterator types used for data manipulation. Additionally, it includes examples of using vectors and lists, demonstrating their constructors and methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT – 5

 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( )

Dr. BAPUJI RAO, Department of CSE(CORE)

STANDARD TEMPLATE LIBRARY (STL)


3

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


Library(STL).

SRM IST, DELHI-NCR CAMPUS


 STL components are defined in the "namespace std".
 To use STL in the program, we must include "using namespace std"
directive.

Dr. BAPUJI RAO, Department of CSE(CORE)


COMPONENTS
4

 The THREE key components of STL are:


• Containers

SRM IST, DELHI-NCR CAMPUS


• Algorithms
• Iterators

CONTAINER
ITERATOR
ALGORITHM ITERATOR CONTAINER
ITERATOR
CONTAINER

Dr. BAPUJI RAO, Department of CSE(CORE)

CONTAINER
5
 A Container is a collection of OBJECTS.
 The objects actually stores data.
 These containers are implemented by TEMPLATE CLASSES.

SRM IST, DELHI-NCR CAMPUS


 Therefore can be easily hold different types of data.

Dr. BAPUJI RAO, Department of CSE(CORE)


ALGORITHM
6

 It is a Procedure that is used to process the data contained in the OBJECTS.


 Algorithms are implemented by the TEMPLATE FUNCTIONS.

SRM IST, DELHI-NCR CAMPUS


 It supports different types of tasks such as Initializing, Searching, Copying,
Sorting, and Merging.

Dr. BAPUJI RAO, Department of CSE(CORE)

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 between the algorithms and containers and does manipulation
of dada stored in the objects in a container.
 Algorithms make use of Iterators to perform operations on the objects stored in
containers.

Dr. BAPUJI RAO, Department of CSE(CORE)


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_iterator
reverse 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.

Dr. BAPUJI RAO, Department of CSE(CORE)

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

Dr. BAPUJI RAO, Department of CSE(CORE)


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.
Dr. BAPUJI RAO, Department of CSE(CORE)
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.


 It resizes 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
vector( )
a new instance of that vector.

 It is a default copy constructor that can be used to create a


vector(const vector &C)
new vector that is a copy of the given vector C.

 It creates a vector that is initialized to contain the elements


vector(iterator start, iterator end )
between start and end.
Dr. BAPUJI RAO, Department of CSE(CORE)
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.
 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 of a
vector<Data_Type> ::iterator vector_name.front( );
vector.
void vector_name.clear( );  It deletes all of the elements in the vector.

 It returns true if the vector has no elements,


bool vector_name.empty( );
false otherwise.
Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE-1
15

#include<vector>
#include<iostream>
using namespace std;
int main()

SRM IST, DELHI-NCR CAMPUS


{
// 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;
}

Dr. BAPUJI RAO, Department of CSE(CORE)


OUTPUT
16

SRM IST, DELHI-NCR CAMPUS


Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE-2
17

#include<vector> OUTPUT
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);
}
}
Dr. BAPUJI RAO, Department of CSE(CORE)
EXAMPLE-3
18

#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; OUTPUT
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);
Dr. BAPUJI RAO, Department of CSE(CORE)

LIST
19

 Lists are sequences of elements stored in a LINKED LIST.


 It allows fast insertions and deletions process in the List.

SRM IST, DELHI-NCR CAMPUS


 It is slower in random access.

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 between
list(iterator start, iterator end )
start and end.

Dr. BAPUJI RAO, Department of CSE(CORE)


LIST METHODS
20

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.
list<data_type>::iterator iterator_name = list_name.begin( );

 It returns an iterator just past the last element of a


list<data_type>::iterator iterator_name = list_name.end( );
list.
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.
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.
Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE-1
21

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

SRM IST, DELHI-NCR CAMPUS


using namespace std; OUTPUT
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;
}

Dr. BAPUJI RAO, Department of CSE(CORE)


EXAMPLE-2
22

// 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"; OUTPUT

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]);

Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE-3
23
// 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]);
}
Dr. BAPUJI RAO, Department of CSE(CORE)
Continue…
// store arr3 elements in list3 from back of the list 24
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;
} Dr. BAPUJI RAO, Department of CSE(CORE)

Continue…
25
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;
}
Dr. BAPUJI RAO, Department of CSE(CORE)
26

SRM IST, DELHI-NCR CAMPUS


OUTPUT

Dr. BAPUJI RAO, Department of CSE(CORE)

DEQUE
27

 It allows fast insertions and deletions at the BEGINNING as


well as the END of the QUEUE.

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
deque(const deque& C)
new 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.

Dr. BAPUJI RAO, Department of CSE(CORE)


DEQUE METHODS
28

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.
deque<data_type>::iterator iterator_name = deque_name.begin( );  It returns an iterator to the beginning of the deque.
 It returns an iterator just past the last element of a
deque<data_type>::iterator iterator_name = deque_name.end( );
deque.
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.
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.
Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE-1
29

// Example of deque constructors and size( ) method.


#include <deque>
#include<iostream>

SRM IST, DELHI-NCR CAMPUS


using namespace std;
OUTPUT
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;
}

Dr. BAPUJI RAO, Department of CSE(CORE)


EXAMPLE-2
30

// EXAMPLE 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; OUTPUT
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;
}
Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE-3
31

// Example 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++) OUTPUT

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;
Dr. BAPUJI RAO, Department of CSE(CORE)
ASSOCIATIVE CONTAINERS
32

 In an associative container the items are not arranged in sequence, but arranged in a Tree
Structure.
 The two main categories of associative containers are SETS and MAPS.

SRM IST, DELHI-NCR CAMPUS


 SET: A set stores objects containing KEYS.
 MAP: A map stores objects containing KEY-VALUE PAIRS.
 The first part of the pair is an object containing a KEY and the second part is an object
containing a VALUE.
 A MULTISET and a MULTIMAP are similar to a SET and a MAP, but can include multiple
instances of the SAME KEY.
 Algorithms, lower_bound() and equal_range() are used in ASSOCIATIVE CONTAINERS.

Dr. BAPUJI RAO, Department of CSE(CORE)

SET CONSTRUCTORS
33

CONSTRUCTORS PURPOSE
 The default set constructor takes no arguments, creates a new
set( )

SRM IST, DELHI-NCR CAMPUS


instance of that set.

 The parameterized constructor creates a set with space for size


set(array_name, array_name + size)
elements of array_name.

 It creates a set by coping the contents of old_set_name in the


set(old_set_name)
newly created set.

 It creates a set that is initialized to contain the elements between


set(iterator start, iterator end )
start and end of the iterable container.

Dr. BAPUJI RAO, Department of CSE(CORE)


SET METHODS
34

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

SRM IST, DELHI-NCR CAMPUS


begin( )
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.
size( )  It returns the number of items in the set.

Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE-1
35

// Example of set constructors


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

SRM IST, DELHI-NCR CAMPUS


#include <set>
cout<<"\n\n Size of set3 = "<<set3.size();
#include <iterator> OUTPUT
using namespace std;
cout<<"\n\n Items of set2 = ";
int main()
for(it=set2.begin(); it!=set2.end(); it++)
{
cout<<" "<<*it;
int arr[]={10,6,9,5,2};
vector<int> v;
cout<<"\n\n Items of set3 = ";
for(int i=4; i>=0; i--)
for(it=set3.begin(); it!=set3.end(); it++)
v.push_back(arr[i]);
cout<<" "<<*it;
cout<<endl;
//declaration of set objects
return 0;
set<int> set1, set2(arr, arr+5);
}
set<int> set3(v.begin(), v.end());
// set iterator
set<int>::iterator it;
Dr. BAPUJI RAO, Department of CSE(CORE)
EXAMPLE-2
36

// set to store integer objects.


#include <iostream>
#include <set> OUTPUT
#include <string>
#include<iterator>
using namespace std;
// To display size of set
int main()
cout<<"\n\n Size of numberSet = "<<numberSet.size()<<endl;
{
cout<<"\n The Numbers From The Set:";
int num;
for(iter = numberSet.begin();iter != numberSet.end(); iter++)
// declaration of set object
cout <<"\n "<<*iter;
set<int, less<int> > numberSet;
cout<<endl;
// iterator to set
return 0;
set<int, less<int> >::iterator iter;
}
for(int i=1; i<=6; i++)
{
cout<<"\n Enter Number-"<<i<<" : ";
cin>>num;
numberSet.insert(num);
}
Dr. BAPUJI RAO, Department of CSE(CORE)

MULTISET EXAMPLE
37
// Example of multiset constructors // declaration of set iterator
and set<int>::iterator it;
// size() method. cout<<"\n\n Items of set1 = ";
#include <iostream> for(it=set1.begin(); it!=set1.end(); it++)
#include <vector> cout<<" "<<*it;
#include <set>

SRM IST, DELHI-NCR CAMPUS


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

// declaration of multiset object OUTPUT


multiset<int> set2(arr, arr+7);
int a = set1.size(), b = set2.size();
cout<<"\n Size of set1 = "<<a;
cout<<"\n\n Size of multiset set2 = "<<b;
Dr. BAPUJI RAO, Department of CSE(CORE)
MAP EXAMPLE
38

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

SRM IST, DELHI-NCR CAMPUS


#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, less<string> > mapStates; // map object declaration

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


Dr. BAPUJI RAO, Department of CSE(CORE)

CONTINUE…
39

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


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

SRM IST, DELHI-NCR CAMPUS


cap = capitals[i]; OUTPUT
// 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;
}
Dr. BAPUJI RAO, Department of CSE(CORE)
MULTIMAP EXAMPLE
40

// Example 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"; Dr. BAPUJI RAO, Department of CSE(CORE)

CONTINUE…
41

// printing multimap mmap1 again OUTPUT


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';
return 0;
}

Dr. BAPUJI RAO, Department of CSE(CORE)


STACK
42

 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.

SRM IST, DELHI-NCR CAMPUS


METHODS PURPOSE
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.

Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE
43

// Example 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; return 0;
s.push(21); }
s.push(2);
s.push(24);
s.push(15);
int num=6;
s.push(num);
// pop three elements from the stack
OUTPUT
s.pop();
s.pop();
s.pop();
Dr. BAPUJI RAO, Department of CSE(CORE)
find( ) ALGORITHM
44

 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);

Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE
// To find the first object with a specified value 45
#include <iostream>
#include <algorithm> //for find( ) algorithm
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;
} Dr. BAPUJI RAO, Department of CSE(CORE)
count( ) ALGORITHM
46

 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


EXAMPLE
#include <iostream>
#include <algorithm> //for count()
using namespace std;
int arr[] = { 30, 20, 30, 40, 30, 50, 60, 70 };
int main( ) OUTPUT
{
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;
}
Dr. BAPUJI RAO, Department of CSE(CORE)

sort( ) ALGORITHM
47

 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>( ));

Dr. BAPUJI RAO, Department of CSE(CORE)


EXAMPLE
48

#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>()); OUTPUT

Dr. BAPUJI RAO, Department of CSE(CORE)

search( ) ALGORITHM
49

 It searches for a container in a given container.


 Syntax:

SRM IST, DELHI-NCR CAMPUS


Data_type *pointer = search(Container1_Begin_Address, Container1_End_Address,
Container2_Begin_Address, Container2_End_Address);

Dr. BAPUJI RAO, Department of CSE(CORE)


EXAMPLE
50

#include <iostream>
#include <algorithm>
using namespace std;
int array[ ] = { 11, 44, 33, 11, 22, 33, 11, 22, 44 };

SRM IST, DELHI-NCR CAMPUS


int sub_array[ ] = { 11, 22, 33 };
int main( ) OUTPUT
{
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;
}

Dr. BAPUJI RAO, Department of CSE(CORE)

merge( ) ALGORITHM
51

 It merges two containers and stores the result in a new container.


 Syntax:

SRM IST, DELHI-NCR CAMPUS


merge(Container1_Begin_Address, Container1_End_Address,
Container2_Begin_Address, Container2_End_Address, Resultant_Container);

Dr. BAPUJI RAO, Department of CSE(CORE)


EXAMPLE
52

#include <iostream>
#include <algorithm> //for merge()
using namespace std;
int arr1[ ] = { 2, 3, 4, 6, 8 };

SRM IST, DELHI-NCR CAMPUS


int arr2[ ] = { 1, 3, 5 };
int result[8]; OUTPUT
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;
}

Dr. BAPUJI RAO, Department of CSE(CORE)

for_each( ) ALGORITHM
53

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

SRM IST, DELHI-NCR CAMPUS


EXAMPLE
OUTPUT
#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 }; }
Dr. BAPUJI RAO, Department of CSE(CORE)
transform( ) ALGORITHM
54

 It changes the container items and stores in the same container or different container.

SRM IST, DELHI-NCR CAMPUS


 Syntax:
tranform(Container_Begin_Address, Container_End_Address, New_Container,
Function_To_Store_In_New_Container);

Dr. BAPUJI RAO, Department of CSE(CORE)

EXAMPLE
55

#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";

SRM IST, DELHI-NCR CAMPUS


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 }

OUTPUT

Dr. BAPUJI RAO, Department of CSE(CORE)


SPECIALIZED ITERATORS
56

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
Dr. BAPUJI RAO, Department of CSE(CORE)

REVERSE ITERATOR EXAMPLE


57

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


#include <list> cout<<"\n\n The Reverse List:\n";
using namespace std; //displaying output

SRM IST, DELHI-NCR CAMPUS


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

list<int>::iterator iter; OUTPUT


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

Dr. BAPUJI RAO, Department of CSE(CORE)


INSERT ITERATOR EXAMPLE
58
// Example of insert iterators with queues
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;

SRM IST, DELHI-NCR CAMPUS


int main( )
 There are three flavors of the insert iterator: {
int arr1[] = { 1, 3, 5, 7, 9 };
• back_inserter inserts new items at the 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;
deque<int> dq3;
• inserter inserts new items at a specified location. // transfer arrays to deques
for(int i=0; i<5; i++)
{
dq1.push_back( arr1[i] );
dq2.push_back( arr2[i] );
dq3.push_back( arr3[i] );
}
Dr. BAPUJI RAO, Department of CSE(CORE)

CONTINUE…
59

// copy dq1 to dq2


cout<<"\n The First Queue:\n"; copy( dq1.begin(), dq1.end(), back_inserter(dq2));

SRM IST, DELHI-NCR CAMPUS


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

Dr. BAPUJI RAO, Department of CSE(CORE)


OUTPUT
60

SRM IST, DELHI-NCR CAMPUS


Dr. BAPUJI RAO, Department of CSE(CORE)

ostream_iterator CLASS
61

 The ostream_iterator object can be used as an argument to any algorithm that specifies an
output iterator.

SRM IST, DELHI-NCR CAMPUS


 Syntax:
ostream_iterator<Data_Type> Output_Iterator_Name(cout, "Separator Character");
copy(begin_iterator, end_iterator, Output_Iterator_Name);

 Examples:
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);
Dr. BAPUJI RAO, Department of CSE(CORE)
EXAMPLE
62

// Example of 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] ); OUTPUT

Dr. BAPUJI RAO, Department of CSE(CORE)

istream_iterator CLASS
63

 The istream_iterator object can be used as an argument to any algorithm that specifies an
input iterator.

SRM IST, DELHI-NCR CAMPUS


 Syntax:
istream_iterator<Data_Type> Input_Iterator_Name(cin);
istream_iterator<Data_Type> end_of_stream;
copy(Input_Iterator_Name, end_of_stream, List_Name.begin( ));

 Examples:
list<float> mylist(5);
istream_iterator<float> input_iterator(cin);
istream_iterator<float> end_of_stream;
copy(input_iterator, end_of_stream, mylist.begin( ));
Dr. BAPUJI RAO, Department of CSE(CORE)
EXAMPLE
64

// Example of istream_iterator
#include <iostream>
#include <list>

SRM IST, DELHI-NCR CAMPUS


#include <algorithm>
#include<iterator>
using namespace std;
int main( )
{
// uninitialized list
list<float> mylist(5);

cout << "\n Enter 5 floating-point numbers: ";


// istream iterators
istream_iterator<float> cin_iter(cin); //cin
istream_iterator<float> end_of_stream; // ctrl + z

Dr. BAPUJI RAO, Department of CSE(CORE)

CONTINUE…
65

//copy from cin to mylist


copy( cin_iter, end_of_stream, mylist.begin());

SRM IST, DELHI-NCR CAMPUS


cout << endl; OUTPUT

//display mylist
ostream_iterator<float> ositer(cout, "\n ");
cout<<"\n\n The Numbers from the List:\n ";
copy(mylist.begin(), mylist.end(), ositer);
cout << endl;
return 0;
}

Dr. BAPUJI RAO, Department of CSE(CORE)

You might also like