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

1432[1]

The document provides an overview of the Standard Template Library (STL) in C++, detailing its key components: containers, algorithms, and iterators. It describes various types of sequence and associative containers, such as vectors, lists, and maps, along with their functionalities and methods. Additionally, it includes code examples demonstrating the use of these containers and their methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

1432[1]

The document provides an overview of the Standard Template Library (STL) in C++, detailing its key components: containers, algorithms, and iterators. It describes various types of sequence and associative containers, such as vectors, lists, and maps, along with their functionalities and methods. Additionally, it includes code examples demonstrating the use of these containers and their methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT – 5 2

 STL
 Containers – Sequence and Associative Container

CAMPUS
SRM IST, DELHI-NCR
 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( )

STANDARD TEMPLATE LIBRARY (STL) 3

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


Library(STL).

CAMPUS
SRM IST, DELHI-NCR
 STL components are defined in the "namespace std".
 To use STL in the program, we must include "using namespace std"
directive.

2
COMPONENTS 4

 The THREE key components of STL are:


• Containers

CAMPUS
SRM IST, DELHI-NCR
• Algorithms
• Iterators

CONTAINER
ITERATOR
ALGORITHM ITERATOR CONTAINER
ITERATOR
CONTAINER

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

CAMPUS
SRM IST, DELHI-NCR
 Therefore can be easily hold different types of data.

4
ALGORITHM 6

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


 Algorithms are implemented by the TEMPLATE FUNCTIONS.

CAMPUS
SRM IST, DELHI-NCR
 It supports different types of tasks such as Initializing, Searching, Copying,
Sorting, and Merging.

ITERATOR 7

 An ITERATOR is an OBJECT that points to an Object in a Container.


 It acts just like a Pointer.

CAMPUS
SRM IST, DELHI-NCR
 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.

6
ITERATOR 8

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

CAMPUS
SRM IST, DELHI-NCR
 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.
7

CLASSIFICATION OF CONTAINERS
9

DERIVED CONTAINERS
(OR)

CAMPUS
SRM IST, DELHI-NCR
SEQUENCE CONTAINERS ASSOCIATIVE CONTAINERS CONTAINER ADAPTORS

VECTOR LIST DEQUEUE SET MULTISET MAP MULTIMAP STACK QUEUE PRIORITY
QUEUE

8
SEQUENCE CONTAINERS
10

SEQUENCE HEADER
DESCRIPTION ITERATOR
CONTAINERS FILE
 A dynamic array.

CAMPUS
SRM IST, DELHI-NCR
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.

9
Mr. BAPUJI RAO, Dept. of CSE

ASSOCIATIVE CONTAINERS
11

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

CAMPUS
SRM IST, DELHI-NCR
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.
10
DERIVED CONTAINERS
12

DERIVED HEADER
DESCRIPTION ITERATOR
CONTAINERS FILE
 A standard stack.
 It is LIFO(Last In First Out), i.e., the

CAMPUS
SRM IST, DELHI-NCR
Stack element inserted last removed first from <stack> No Iterator

the stack.
 A standard queue.
 It is FIFO(First In First Out), i.e., the
Queue element inserted first removed first from <queue> No Iterator

the queue.
 It is priority queue.
Priority Queue  The element with the highest priority is <queue> No Iterator
removed first from the queue. 11
Mr. BAPUJI RAO, Dept. of CSE

VECTOR
13

 Vectors are the dynamic arrays.


 It resizes them automatically when an element is inserted or deleted.

CAMPUS
SRM IST, DELHI-NCR
 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.
12
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.

CAMPUS
SRM IST, DELHI-NCR
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.
13

EXAMPLE-1
15

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

CAMPUS
SRM IST, DELHI-NCR
{
// 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;
}
14
OUTPUT
16

CAMPUS
SRM IST, DELHI-NCR
15

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;

CAMPUS
SRM IST, DELHI-NCR
{
// 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);
v1.push_back(20); // pop the last element of Vector, v2
cout<<endl<<endl; v2.pop_back();
// store numbers in Vector, v2
for(int i=0, num; i<5; i++) cout<<"\n Now Vector, v2 Elements:\n";
{ for(int i=0; i<v2.size(); i++)
cout<<" Enter a Number : "; cout<<" "<<v2[i]<<endl;
cin>>num;
return 0;
v2.push_back(num);
} }
16
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( )

CAMPUS
SRM IST, DELHI-NCR
{ 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);
17

LIST 19

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


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

CAMPUS
SRM IST, DELHI-NCR
 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.
18
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.

CAMPUS
SRM IST, DELHI-NCR
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.
19

EXAMPLE-1
21

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

CAMPUS
SRM IST, DELHI-NCR
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;
}
20
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

CAMPUS
SRM IST, DELHI-NCR
#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]);
21

EXAMPLE-3
23
// Demonstration of merging of two lists
#include <list>
#include<iostream>
#include<iterator>
using namespace std;
int main( )

CAMPUS
SRM IST, DELHI-NCR
{
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]);
}
22
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);

CAMPUS
SRM IST, DELHI-NCR
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;
23
} Dr. BAPUJI RAO, Department of CSE(CORE)

Continue…
cout<<"\n\n The List4 Elements:";
25

for(it=list4.begin(); it!=list4.end(); it++)


{
cout <<"\n "<<*it;
}

CAMPUS
SRM IST, DELHI-NCR
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;
}
24
26

CAMPUS
SRM IST, DELHI-NCR
OUTPUT

25

DEQUE 27

 It allows fast insertions and deletions at the BEGINNING as


well as the END of the QUEUE.

CAMPUS
SRM IST, DELHI-NCR
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.

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

CAMPUS
SRM IST, DELHI-NCR
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.
27

EXAMPLE-1
29

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


#include <deque>
#include<iostream>

CAMPUS
SRM IST, DELHI-NCR
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;
}

28
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>

CAMPUS
SRM IST, DELHI-NCR
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;
} 29

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

CAMPUS
SRM IST, DELHI-NCR
#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; 30
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.

CAMPUS
SRM IST, DELHI-NCR
 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.

31

SET CONSTRUCTORS
33

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

CAMPUS
SRM IST, DELHI-NCR
 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.

32
SET METHODS
34

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

CAMPUS
SRM IST, DELHI-NCR
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.

33

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

CAMPUS
SRM IST, DELHI-NCR
#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;
34
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);
}
35

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>

CAMPUS
SRM IST, DELHI-NCR
#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); }
OUTPUT
// declaration of multiset object
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;
36
MAP EXAMPLE
38

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

CAMPUS
SRM IST, DELHI-NCR
#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


37

CONTINUE…
39

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


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

CAMPUS
SRM IST, DELHI-NCR
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;
}
38
MULTIMAP EXAMPLE
40

// Example of multimap program


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

CAMPUS
SRM IST, DELHI-NCR
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";
39
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)

CAMPUS
SRM IST, DELHI-NCR
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;
}
40
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.

CAMPUS
SRM IST, DELHI-NCR
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.

41

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

CAMPUS
SRM IST, DELHI-NCR
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();
42
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.

CAMPUS
SRM IST, DELHI-NCR
 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);

43

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

CAMPUS
SRM IST, DELHI-NCR
{
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;
44
} 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);

CAMPUS
SRM IST, DELHI-NCR
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;
} 45

sort( ) ALGORITHM
47

 It sorts a container in ascending and descending order.


 Syntax for Ascending Order:

CAMPUS
SRM IST, DELHI-NCR
sort(Container_Begin_Address, Container_End_Address);
 Syntax for Descending Order:
sort(Container_Begin_Address, Container_End_Address, greater<Data_Type>( ));

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

CAMPUS
SRM IST, DELHI-NCR
//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

47

search( ) ALGORITHM
49

 It searches for a container in a given container.


 Syntax:

CAMPUS
SRM IST, DELHI-NCR
Data_type *pointer = search(Container1_Begin_Address, Container1_End_Address,
Container2_Begin_Address, Container2_End_Address);

48
EXAMPLE
50

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

CAMPUS
SRM IST, DELHI-NCR
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;
}

49

merge( ) ALGORITHM
51

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


 Syntax:

CAMPUS
SRM IST, DELHI-NCR
merge(Container1_Begin_Address, Container1_End_Address,
Container2_Begin_Address, Container2_End_Address, Resultant_Container);

50
EXAMPLE
52

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

CAMPUS
SRM IST, DELHI-NCR
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;
}
51

for_each( )ALGORITHM
53

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

CAMPUS
SRM IST, DELHI-NCR
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 }; }
52
transform( ) ALGORITHM
54

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

CAMPUS
SRM IST, DELHI-NCR
 Syntax:
tranform(Container_Begin_Address, Container_End_Address, New_Container,
Function_To_Store_In_New_Container);

53

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

CAMPUS
SRM IST, DELHI-NCR
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

54
SPECIALIZED ITERATORS
56

ITERATOR ADAPTERS STREAM ITERATORS


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

CAMPUS
SRM IST, DELHI-NCR
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
55

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

CAMPUS
SRM IST, DELHI-NCR
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;
56
INSERT ITERATOR EXAMPLE
58
// Example of insert iterators with queues
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;

CAMPUS
SRM IST, DELHI-NCR
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] );
}
57

CONTINUE…
59

• // copy dq1 to dq2


cout<<"\n The First Queue:\n";
• copy( dq1.begin(), dq1.end(), back_inserter(dq2));
CAMPUS
SRM IST, DELHI-NCR
for(int i=0; i<dq1.size(); i++)
cout<<' '<<dq1[i];
• cout<<"\n The Second Queue After Insertion of First Queue At
cout<<"\n The Second Queue:\n";
The End:\n"; for(int i=0;
for(int i=0; i<dq2.size(); i++)
i<dq2.size();
// copy dq1 to dq3 i++) //display dq2
copy( dq1.rbegin(), dq1.rend(), front_inserter(dq3));
• cout <<' '<<dq2[i]; cout<<"\n The Third Queue After Insertion of First Queue At The Begin:\n";
cout<<' '<<dq2[i];

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

58
OUTPUT
60

CAMPUS
SRM IST, DELHI-NCR
59

ostream_iterator CLASS
61

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

CAMPUS
SRM IST, DELHI-NCR
 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);
60
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>

CAMPUS
SRM IST, DELHI-NCR
#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

61

istream_iterator CLASS
63

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

CAMPUS
SRM IST, DELHI-NCR
 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( ));
62
EXAMPLE
64

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

CAMPUS
SRM IST, DELHI-NCR
#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
63

CONTINUE…
65

//copy from cin to mylist


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

CAMPUS
SRM IST, DELHI-NCR
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;
}

64

You might also like