Final
Final
BY
Mrs. Shubhangi Vairagar
DIT Pimpri
STANDARD TEMPLATE LIBRARY
• Introduction to STL
Containers
Algorithms
Iterators
2
COMPONENTS OF STL
Algorithms use iterators to interact with objects
stored in containers
Container
Algorithm1 Algorithm 2
Object1 Object2
Iterator 1 Iterator 2
Object3 Iterator 3
Algorithm 3
3
CONTAINER
Implemented by Template
Classes
4
ALGORITHM
Example :
These are procedures
used to process the data Searching, Sorting,
contained in containers. Merging, Copying,
Initializing
Implemented by
template functions
5
ITERATOR
They can be
Connect Algorithms
incremented and
with Containers
decremented
6
COMPONENTS OF STL
Containers
7
CATEGORIES OF CONTAINERS
Sequence
Containers
Derived
Containers Associative
: Container Containers
Adapters
8
CONTAINERS
9
CATEGORIES OF CONTAINERS
10
Common member functions for most
STL Contaiers
Constructs an empty container.
default constructor
Containers will have other constructors as well.
Construct a copy of an already existing container
copy constructor
of the same type.
destructor Clean up when container no longer needed.
operator= Assign one container to another.
operator== Test for equality, lexicographically.
operator!= Test for inequality, lexicographically.
operator< Test for less than, lexicographically.
operator<= Test for less than or equal to, lexicographically.
operator> Test for greater than, lexicographically.
operator>= Test for greater than or equal to, lexicographically.
Commom member functions for most
STL Contaiers
empty Test if container is empty.
max_size Return maximum number of components container can hold.
size Return number of elements container currently holds.
swap Exchange all components with those of another container.
insert Insert one or more components into a container.
erase Erases one or more components from a container.
clear Erases all components from a container.
Return an iterator or const_iterator pointing to the first
begin
component.
Return an iterator or const_iterator pointing to one-past-the-last
end
component.
Return a reverse_iterator or const_reverse_iterator pointing to
rbegin
the last component.
Return a reverse_iterator or const_reverse_iterator pointing to
rend
one-before-the-first component.
Member functions found only
in sequential STL containers
10
SEQUENCE CONTAINERS
Stores elements in a linear sequence
Example
vector
deque list
12
Vector : Sequence Container
Expandable and dynamic array
14
vector Sequence Container
Declarations
◦ vector <type> v;
type: int, float, etc.
Iterators
◦ vector<type>::const_iterator iterVar;
const_iterator cannot modify elements
◦ vector<type>::reverse_iterator iterVar;
Visits elements in reverse order (end to beginning)
Use rbegin to get starting point
Use rend to get ending point
15
vector Sequence Container
vector functions
◦ v.push_back(value)
Add element to end (found in all sequence containers).
◦ v.size()
Current size of vector
◦ v.capacity()
How much vector can hold before reallocating memory
Reallocation doubles size
◦ vector<type> v(a, a + SIZE)
Creates vector v with elements from array a up to (not
including) a + SIZE
16
vector Sequence Container
vector functions
◦ v.insert(iterator, value )
Inserts value before location of iterator
◦ v.insert(iterator, array , array + SIZE)
Inserts array elements (up to, but not including array + SIZE) into
vector
◦ v.erase( iterator )
Remove element from container
◦ v.erase( iter1, iter2 )
Remove elements starting from iter1 and up to (not including)
iter2
◦ v.clear()
Erases entire container
17
vector Sequence Container
vector functions operations
◦ v.front(), v.back()
Return first and last element
◦ v.[elementNumber] = value;
Assign value to an element
18
Vector : Sequence Container
int array[5] = {12, 7, 9, 21, 13 };
vector<int> v(array,array+5);
12 7 9 21 13
v.pop_back(); v.push_back(15);
12 7 9 21 12 7 9 21 15
0 1 2 3 4
12 7 9 21 15
19
v.begin(); v[3]
Vector : Sequence Container
#include <vector>
#include <iostream>
using namespace std;
void main
{
int arr[] = {12, 7, 9, 21, 13 }; // standard C array
vector<int> v(arr, arr+5); // initialize vector with C array
13 21 9 7 12
12 7 9 21 13
21
Vector : Using Iterator
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector <int> vec1;
vector <int>::iterator vec1_Iter;
vector <int>::reverse_iterator vec1_rIter;
vec1.push_back(10);
vec1.push_back(7);
vec1.push_back(3);
22
Vector : Using Iterator
cout<<"vec1 data: ";
for(int i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"\nOperation: vec1.begin()\n";
vec1_Iter = vec1.begin();
cout<<"\nOperation: vec1.rbegin()\n";
vec1_rIter = vec1.rbegin();
cout<<"The first element of the reversed vec1 is “;
cout<<*vec1_rIter<<endl;
return 0; 23
}
O/P of previous program
vec1 data: 10 7 3
Operation: vec1.begin()
The first element of vec1 is10
Operation: vec1.rbegin()
The first element of the reversed vec1 is : 3
24
Vector : Using Iterator
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector <int> vec1;
vector <int>::reverse_iterator key;
vec1.push_back(7);
vec1.push_back(3);
vec1.push_back(4);
vec1.push_back(1);
25
Vector : Using Iterator
cout<<"Operation: vec1.rbegin() and vec1.rend()\n";
cout<<"vec1 data: ";
26
O/P of previous program
Operation: vec1.begin() and vec1.rend()
vec1 data: 1 4 3 7
27
deque : Sequence Container
Double ended Queue
28
deque : Sequence Container
29
Deque
#include <iostream>
#include <deque>
using namespace std;
int main ()
{
deque<int> mydeque;
mydeque.push_back (100);
mydeque.push_back (200);
mydeque.push_back (300);
30
Deque
cout << "Popping out the elements in mydeque:";
while (!mydeque.empty())
{
cout << mydeque.front();
mydeque.pop_front();
}
return 0;
}
31
O/P of previous program
The final size of mydeque is : 3
32
list : Sequence Container
Bidirectional
33
list : Sequence Container
34
List
#include <iostream.h>
#include <list>
main()
{
list <char> l;
list <char>::iterator p;
l.push_back('o');
l.push_back('a');
l.push_back('t');
p=l.begin(); 35
List
cout <<" "<< *p<<endl; // p refers to the 'o' in ('o', 'a', 't')
print(l);
l.insert(p, 'c'); // l is now ('c', 'o', 'a', 't') and p still refers to
'o‘
cout <<" "<< *p<<endl;
print(l);
l.erase(p);
print(l); 36
l.erase(l.begin()); //removes front of l
print(l);
37
O/P of previous program
o
oat
o
coat
null
cat
38
at
Comparison of sequence containers
39
ASSOCIATIVE CONTAINERS
Non-sequential
40
FOUR TYPES OF ASSOCIATIVE
CONTAINERS
All these
store data in
a structure set
called tree
which
facilitates fast
searching
multimap Multiset
map
41
Set & Multiset : Associative
Container
Stores a number of items which contain key
42
Set
#include <iostream>
#include <string>
#include <set>
int main()
{
string a[] = {"Alice", "Bob", "Carl", "Dick", "Eve", "Fred“} ;
set<string> s(a, a+6);
set<string>::iterator p = s.begin();
while (p != s.end())
cout << *p++ << endl;
cout<<_______________________”<<endl; 43
Set
set<string>::size_type numberDeleted = s.erase(“Bob");
p = s.begin();
while (p != s.end()) cout << *p++ << endl;
cout<<_______________________”<<endl;
numberDeleted = s.erase(“William");
p = s.begin();
while (p != s.end()) cout << *p++ << endl;
cout<<_______________________”<<endl;
s.erase(s.begin());
p = s.begin();
while (p != s.end()) cout << *p++ << endl;
cout<<_______________________”<<endl;
s.erase(s.find("Carl"), s.find(“Eve"));
p = s.begin();
while (p != s.end()) cout << *p++ << endl; 44
Set
cout<<_______________________”<<endl;
s.clear();
if (s.empty())
cout << "\nThe set is now empty.";
45
O/P of previous program
Alice
Bob
Carl
Dick
Eve
Fred
____________________
Alice
Carl
Dick
Eve 46
Fred
O/P of previous program
Alice
Carl
Dick
Eve
Fred
____________________
____________________
Carl
Dick
Eve
Fred 47
O/P of previous program
Fred
____________________
48
MultiSet
#include <iostream>
#include <string>
#include <set>
class Book
{
public :
Book()
{
title = author = publisher = date = "";
}
Book(string a)
{
author = a;
title = publisher = date = ""; 49
}
MultiSet
Book(string t, string a, string p, string d)
{
title = t;
author = a;
publisher = p;
date = d;
}
string Author()
{
return author;
}
50
MultiSet
void GetInfo(string &t, string &a, string &p, string &d)
{
t = title;
a = author;
p = publisher;
d = date;
}
private:
string author;
string title;
string publisher;
string date;
};
51
Multiset
int main()
{
multiset<Book> b;
string a;
multiset<Book>::iterator p = b.begin();
while (p != bookList.end())
{
cout<<*p++<<endl;
}
}; 52
O/P of previous program
C++ book
ABC
McGraw-Hill
1998
Java
XYZ
BB Publisher
2001
Let Us C
Kanetkar
McGraw-Hill
1997 46
Map & Multimap : Associative
Container
Stores pair of items, one called key and other
value
24
Map
#include <map>
#include <algorithm>
#include <iostream>
#include <string>
int main() {
map<string,int> amap;
amap[”First”]=1;
amap[“Second”]=2;
amap["Third"]=3;
amap[”Fourth"]=4;
cout << "Size : " << amap.size() << endl; 71
61
Map
map<string,int>::iterator it;
71
62
THREE TYPES OF DERIVED
CONTAINERS
These are
known as stack
container
adaptors
priority_queue queue
25
Stack, Queue, Priority_Queue
#include <stack>
#include <queue>
using namespace std;
int main()
{
// STL Stack
stack<int, vector<int> > S; // Changing default container
Containers
Algorithms
Iterators
27
2. ALGORITMS
Generic functions that handle common tasks
such as searching, sorting, comparing,
and editing
Mutating
Relational
(Modifying)
Set Sorting 29
Non-Mutating Algorithms
Operations Description
32
Mutating Algorithms
Copy() Copy range of elements (function template )
38
Algorithms
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
vector<int> v;
vector<int>p;
v.push_back(10); v.push_back(20); v.push_back(10);
p.push_back(60); v.push_back(40); v.push_back(50);
swap(v,p);
}
Algorithms
int n, value,arr[10],i;
int *Limit = arr + n;
sort(arr, Limit);
Algorithms
cout<<“ Sorted List is” ;
for(i =0; i< n;++i)
{
cout<<arr[i];
cout<<endl;
}
return 0;
}
Algorithm…Searching Example
find , search , binary search
/ binary_search example
#include <iostream> // std::cout
#include <algorithm> // std::binary_search, std::sort
#include <vector> // std::vector
vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1
vector<int>::iterator it;
Algorithm…Searching Example
find , search , binary search
// using default comparison:
sort (v.begin(), v.end());
Output:
return 0;
}
looking for a 3... found!
looking for a 6... not found.
Algorithm…Min Max Example
/ min max example
#include <iostream> // std::cout
#include <algorithm>
int main ()
{
cout<<“\n min(20,10) = “ <<min(20,10);
cout<<“\n min(‘a’,’b) – “ <<min(‘a’,’b’);
cout<<“\n max(‘e’, ‘f’) = <<max(‘e’,’f’);
}
Algorithm…Set Union Example
#include <iostream> // std::cout
#include <algorithm>
#include <vector> // std::vector
int main ()
{
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0
vector<int>::iterator it;
std::sort (first,first+5); // 5 10 15 20 25
std::sort (second,second+5); // 10 20 30 40 50
Algorithm…Set OperationsExample
it= set_union (first, first+5, second, second+5, v.begin());
// 5 10 15 20 25 30 40 50 0 0
v.resize(it-v.begin()); // 5 10 15 20 25 30 40 50
cout << "The union has " << (v.size()) << " elements:\n";
for (it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
} Output:
std::sort (first,first+5); // 5 10 15 20 25
std::sort (second,second+5); // 10 20 30 40 50
Algorithm…Set Intersection
Example
it= set_intersection (first, first+5, second, second+5, v.begin());
// 5 10 15 20 25 30 40 50 0 0
v.resize(it-v.begin()); // 5 10 15 20 25 30 40 50
cout << "The intersection has has " << (v.size()) << " elements:\n";
for (it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
} Output:
cout << "The intersection has has " << (v.size()) << " elements:\n";
for (it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
} Output:
input
random
forward bidirectional
access
output
39
Input & Output Iterator
40
Forward Iterator
41
Bi-directional Iterator
42
Random – Access Iterator
43
Iterators and their characteristics
Iterator Access Direction of I/O
Method Movement Capability
Input Linear Forward Read
Output Linear Forward Write
Forward Linear Forward Read/Write
Bi- Linear Forward & Read/Write
directional Backward
Random Random Forward & Read/Write
Access Backward
44
Operations Supported by Iterators
Iterator Elemen Read Write Increme Compari
t Access nt son
Input v=*p ++ ==, !=
Output *p=v ++
Forward v=*p *p=v ++ ==, !=
Bi- v=*p *p=v ++,-- ==, !=
direction
al
Random v=*p *p=v ++,--,+,- ==,
Access !=,<,>,
& [ ] <=,>=
45
Iterator
vector<int>
array_ 17
vector<int>::iterator
4
23
12 The iterator corresponding to
the class vector<int> is of
size_ 4 the type
vector<int>::iterator
46
Iterator
The member functions begin() and end() return an
iterator to the first and past the last element of a
container
vector<int> v
v.begin()
array_ 17
4
23
12 v.end()
size_ 4
47
Iterator
One can have multiple iterators pointing to
different or identical elements in the container
vector<int> v
i1
array_ 17
4
i2
23
12
i3
size_ 4
48
Istream & ostream iterator…Input
& output iterator Example
// istream_iterator example
#include <iostream> // std::cin, std::cout
#include <iterator> // std::istream_iterator
int main () {
double value1, value2;
std::cout << "Please, insert two values: ";
std::istream_iterator<double> iit (std::cin); // stdin iterator
std::ostream_iterator<int> ot(std””cout,” ”);
value1=*iit;
++iit;
value2=*iit;
std::cout << value1 << "*" << value2 << "=" << (value1*value2) <<
'\n';
return 0; }
Inserter Example
#include <iostream> // std::cout
#include <iterator> // std::front_inserter
#include <list> // std::list
#include <algorithm> // std::copy
int main ()
{
list<int> l1, l2;
for (int i=1; i<=5; i++)
{
l1.push_back(i);
l2.push_back(i*10);
}
Inserter Example …Continued
list<int>::iterator it = l1.begin();
advance (it,3);
copy (l2.begin() , l2.end() , inserter(l1,it));
int x;
cout<<”Enter Five values “;
for(i=0;i<5;i++)
{
cin>>x;
v.push_back(x); //Putting values into vector
} 50
Vector
cout<<“Size after adding 5 values : “ <<v.size() <<“\n”;
display(v);
56
Functions of vector
Function Name Description
empty( ) Returns true if the vector is
empty. Otherwise, it returns
false.
Example:
if (vect.empty())
cout << "The
vector is empty.";
The statement above displays
the message if vect is
57
empty.
Functions of vector
Function Name Description
pop_back() Removes the last element
from the vector.
Example:
vect.pop_back();
The statement above
removes the last element of
vect, thus reducing its size
by 1.
58
Functions of vector
Function Name Description
push_back(va Stores a value in the last
lue) element of the vector. If the
vector is full or empty, a new
element is created.
Example:
vect.push_back(7);
The statement above stores
7 in the last element of
vect.
59
Functions of vector
Function Name Description
reverse() Reverses the order of the
elements in the vector (the last
element becomes the first
element, and the first element
becomes the last element.)
Example:
vect.reverse();
The statement above reverses
the order of the element in
vect.
60
Functions of vector
Function Name Description
resize(eleme Resizes a vector by elements
nts, value) elements. Each of the new
elements is initialized with the
value in value.
Example:
vect.resize(5, 1);
The statement above increases
the size of vect by 5 elements.
The 5 new elements are
initialized to the value 1.
61
Functions of vector
Function Name Description
swap(vector2 Swaps the contents of the vector
) with the contents of vector2.
Example:
vect1.swap(vect2);
The statement above swaps the
contents of vect1 and vect2.
62
Functions of vector
Function Name Description
erase(srcpos, Erases the contents of the vector
destpos) from Source position to
Destination position
Example:
vect1.erase(1,5);
The statement above erases the
contents of vect1 from position
1 to 5.
63
List
#include<list>
#include<iostream>
#include<cstdlib> //For rand( )
using namespace std;
for(i=0;i<3;i++)
list1.push_back(rand( )/100 );
list<int>::iterator p;
for(p=list2.begin(); p!= list2.end();++p)
*p = rand( ) /100;
66
list
cout<< “List1 : “ <<“\n”; 0 184 63
display(list1);
cout<< “List2 : “ <<“\n”;
265 191 157 114 293
display(list2);
display(list1);
display(list2); 67
list
list<int> listA, listB;
listA = list1;
listB = list2;
100 0 184 63 200 191 157 114 293
return(0);
}
68
Thank you