21csc101t Oodp Unit-5
21csc101t Oodp Unit-5
UNIT-5
Standard Template Library
What is STL???
• vector
Implement data structures which • list
can be accessed in a sequential • deque
manner. • arrays
• forward-list
Topic : Sequence Container: Vector List
Sequence Containers: Vector
• Vectors are same as dynamic arrays with the ability to resize itself
automatically when an element is inserted or deleted, with their
storage being handled automatically by the container.
• Vector elements are placed in contiguous storage so that they can be
accessed and traversed using iterators.
• In vectors, data is inserted at the end.
• Inserting at the end takes differential time, as sometimes there may
be a need of extending the array.
• Removing the last element takes only constant time because no
resizing happens.
• Inserting and erasing at the beginning or in the middle is linear in
time.
Functions
associated with the
vector
Iterators
begin() end() rbegin() rend() cbegin() cend() crbegin() crend()
int main()
{
vector<int> g1;
Output:
for (int i = 1; i <= 5; i++)
g1.push_back(i);
Output of begin and end: 1 2 3 4 5
Output of cbegin and cend: 1 2 3 4 5
cout << "Output of begin and end: "; Output of rbegin and rend: 5 4 3 2 1
for (auto i = g1.begin(); i != g1.end(); ++i) Output of crbegin and crend : 5 4 3 2 1
cout << *i << " ";
return 0;
}
functions associated with the vector
Capacity
int main()
{
vector<int> g1;
return 0;
}
functions associated with the vector
Element access
reference operator
at(g) front() back() data()
[g]
Returns a direct
Returns a reference Returns a reference Returns a reference pointer to the
Returns a reference memory array used
to the element at to the element at to the first element to the last element
position ‘g’ in the position ‘g’ in the in the vector internally by the
in the vector vector to store its
vector vector
owned elements.
// C++ program to illustrate the element accesser in vector
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> g1;
Modifiers
It is used to
It is used to It is used to swap It extends the insert a new
It assigns new It is used to pop It inserts new It is used to
It pushes the remove elements the contents of container by element into the
value to the or remove elements before remove all the
elements into a from a container one vector with inserting new vector container,
vector elements elements from a the element at elements of the
vector from the from the another vector of element at the new element
by replacing old vector from the the specified vector container
back specified position same type. Sizes position is added to the
ones back. position
or range. may differ. end of the vector
Sequence Container: List
List 1 (gqlist1) is : 0 2 4 6 8 10 12 14 16 18
List 2 (gqlist2) is : 27 24 21 18 15 12 9 6 3 0
gqlist1.front() : 0
gqlist1.back() : 18
gqlist1.pop_front() : 2 4 6 8 10 12 14 16 18
gqlist2.pop_back() : 27 24 21 18 15 12 9 6 3
gqlist1.reverse() : 18 16 14 12 10 8 6 4 2
gqlist2.sort(): 3 6 9 12 15 18 21 24 27
functions associated with the Lists
returns a constant
end() function returns a constant reverse iterator
returns a reverse returns a constant
begin() function returns an iterator reverse iterator which points to
returns a reverse iterator which random access returns a constant the theoretical
returns an iterator pointing to the which points to
iterator which points to the iterator which random access
pointing to the theoretical last the last element of element preceding
points to the last position before the points to the iterator which points
first element of element which the list i.e reversed the first element in
element of the list. beginning of the beginning of the to the end of the list.
the list follows the last beginning of the list i.e. the
list. list.
element. container. reverse end of the
list.
functions associated with the Lists
function is used to
insert a new function is used to
Removes all element into the insert a new function is used to
Returns the duplicate element into the remove all the
maximum number list container, the
consecutive new element is list container, the elements of the
of elements a list elements from the new element is list container, thus
container can hold. added to the
list. beginning of the added to the end making it size 0.
list. of the list.
functions associated with the Lists
operator= swap() splice() merge() emplace()
Returns a constant
Returns a reverse iterator pointing to
Inserts an element. Returns a reverse iterator which Returns the
the first element of
And returns an iterator which points to the maximum number Assign values to Function which
the container, that
iterator that points points to the last position before the of elements that a the same or changes the size of
is, the iterator
to the first of the element of the beginning of the cannot be used to deque container different deque the deque.
newly inserted deque (i.e., its deque (which is can hold. container.
modify, only
elements. reverse beginning). considered its traverse the
reverse end). deque.
#include <iostream>
#include <deque>
using namespace std;
return 0;
}
Methods of Deque
push_front() push_back() pop_front() pop_back() front() back() clear() erase() empty() size()
Is used to return
Is used to remove Is used to remove Is used to check if the size of the
This function is This function is Is used to pop or Is used to Is used to elements from a
Is used to pop or all the elements of the deque deque container
used to push used to push remove elements reference the first reference the last container from
remove elements the deque container is empty or the number of
elements into a elements into a from a deque element of the element of the the specified
from a deque container, thus or not. elements in the
deque from the deque from the from the back. deque container. deque container. position or range.
from the front. making its size 0. deque container.
front. back.
Sequence Containers: Array
The introduction of array class from C++11 has offered a better alternative for C-
style arrays. The advantages of array class over C-style array are :-
Array classes knows its own size, whereas C-style arrays lack this property. So
when passing to functions, we don’t need to pass size of Array as a separate
parameter.
With C-style array there is more risk of array being decayed into a pointer. Array
classes don’t decay into pointers
Array classes are generally more efficient, light-weight and reliable than C-style
arrays.
Operations on array
return 0; }
Operations on array
front() back()
return 0;
}
Operations on array
size() max_size()
return 0;
}
Operations on array
size() max_size()
empty() fill()
a)10 20 30
b)Garbage Value
c)Syntax error
d)Runtime error
4.Which of the following class template are based on arrays?
a) vector
b) list
c) dequeue
d) both vector & dequeue
Topic : STL Stack
STL Stack
• Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is
added at one end and (top) an element is removed from that end only.
• Stack uses an encapsulated object of either vector or deque (by default) or list (sequential container class)
as its underlying container, providing a specific set of member functions to access its elements.
Stack Syntax:-
• For creating a stack, we must include the <stack> header file in our code. We then use this syntax to define
the std::stack:
• template <class Type, class Container = deque<Type> > class stack;Type – is the Type of element contained
in the std::stack. It can be any valid C++ type or even a user-defined type.
Example:
#include <iostream>
#include <stack>
using namespace std;
int main() {
OUTPUT : 22 21
stack<int> stack;
stack.push(21);
stack.push(22);
stack.push(24);
stack.push(25);
stack.pop();
stack.pop();
while (!stack.empty()) {
cout << stack.top() <<" ";
stack.pop();
}
}
Functions associated with stack
Time Complexity : Time Complexity : Time Complexity : Time Complexity : Time Complexity :
O(1) O(1) O(1) O(1) O(1)
// CPP program to demonstrate working of STL stack
#include <iostream>
#include <stack>
using namespace std;
int main ()
{
stack <int> s;
Output:
s.push(10); The stack is : 1 5 20 30 10
s.push(30); s.size() : 5
s.push(20);
s.push(5); s.top() : 1
s.push(1); s.pop() : 5 20 30 10
cout << "The stack is : ";
showstack(s);
return 0;
}
List of functions of Stack
top()
empty()
push()
swap()
emplace()
stack::top() top() function is used to
reference the top(or the newest) // Application of top() function
#include <iostream>
element of the stack.
#include <stack>
Syntax : using namespace std;
stackname.top()
int main()
Parameters: No value is needed to {
pass as the parameter. int sum = 0;
Return Value: Direct reference to the stack<int> mystack;
mystack.push(1);
top element of the stack
mystack.push(8);
container. mystack.push(3);
mystack.push(6);
mystack.push(2);
OUTPUT : 20
// Stack becomes 1, 8, 3, 6, 2
Time Complexity: O(n) while (!mystack.empty()
Auxiliary Space: O(n) sum = sum + mystack.top();
mystack.pop();
}
cout << sum;
return 0;
}
1. What is the Standard Template Library?
a) Set of C++ template classes to provide common programming data structures and functions
b) Set of C++ classes
c) Set of Template functions used for easy data structures implementation
d) Set of Template data structures only.
Answer: a
STL expanded as Standard Template Library is set of C++ template classes to provide common
programming data structures and functions.
• Copy()
• Copy_backward()
Algorithms : find()
• InputIterator find (InputIterator first, InputIterator last, const T& val);
• The find() algorithm looks for an element matching val between start and
end.
• If an element matching val is found, the return value Is an iterator that
points to that element. Otherwise, the return value is an iterator that points
to end.
#include <iostream>
#include <algorithm>
using namespace std;
int main () {
int myints[] = { 10, 20, 30, 40 };
int * p = find (myints, myints+4, 30);
if (p != myints+4) cout << "Element found in myints: " << *p << '\n';
else cout << "Element not found in myints\n“;
return 0; }
Find() Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
int key;
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
cout << ”enter value :”;
cin >> key;
iter=find(v.begin(),v.end(),key); // finds integer key in v
if (iter != v.end()) // found the element
cout << ”Element ” << key << ” found” << endl;
else
cout << ”Element ” << key << ” not in vector v” << endl;
Find_If() Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
Bool mytest(int n) { return (n>21) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
iter=find_if(v.begin(),v.end(),mytest);
// finds element in v for which mytest is true
if (iter != v.end()) // found the element
cout << ”found ” << *iter << endl;
else
cout << ”not found” << endl;
Algorithm: count()
#include <iostream>
• count() returns the number of elements
in the given range that are equal to given #include <algorithm>
value. #include <vector>
• Syntax for count is: using namespace std;
• count(first ,last ,value) : This will int main ()
return number of the element in {
range defined int values[] =
• by iterators first and last ( excluded ) {5,1,6,9,10,1,12,5,5,5,1,8,9,7,46};
which are equal ( == ) the value int count_5 = count(values, values+15, 5);
/* now count_5 is equal to 4 */
vector<int> v(values, values+15);
int count_1 = count(v.begin(), v.end(), 1);
/* now count_1 is equal to */
return 0;
}
Count_If() Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
Bool mytest(int n) { return (n>14) && (n <36); };
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C
array
vector<int> v(arr, arr+7); // initialize vector with C
array
int n=count_if(v.begin(),v.end(),mytest);
// counts element in v for which mytest is true
cout << ”found ” << n << ” elements” << endl;
Algorithms : search
• This function is used to perform searches for a given sequence in a
given range. There are two variations of the search():
7
Algorithms : Search Example 1
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int inputs1[] = { 1,2,3,4,5,6,7,8};
int inputs2[] = { 2,3,4};
vector<int> v1(inputs1, inputs1+9);
vector<int> v2(inputs2, inputs2+3);
vector<int>::iterator i ,j;
8
Algorithms : sort()
• This function of the STL, sorts the contents of the given range.
There are two version of sort() :
• sort(start_iterator, end_iterator ) : sorts the range defined by
iterators start_iterator and end_iterator in ascending order.
• sort(start_iterator, end_iterator, compare_function) : this also
sorts the given range but you can define how the sorting should be
done by compare_function.
9
Algorithms : sort() Example 1
#include<iostream> v1.push_back(5);
#include<algorithm> v1.push_back(1);
#include<vector>
/* now the vector v1 is 8,4,5,1 */
using namespace std;
vector<int>::iterator i, j;
bool compare_function(int i, int j) i = v1.begin(); // i now points to beginning of the vector v1
{
j = v1.end(); // j now points to end of the vector v1
return i > j; // return 1 if i>j else 0
} sort(i,j); //sort(v1.begin() , v1.end() ) can also be used
bool compare_string(string i, string j) /* now the vector v1 is 1,4,5,8 */
{
return (i.size() < j.size()); /* use of compare_function */
} int a2[] = { 4,3,6,5,6,8,4,3,6 };
sort(s,s+4,compare_string);
v1.push_back(8);
/* now s is "a","ab","abc","abcde" */
v1.push_back(4); }
10
Algorithm: merge()
Combines the elements in the sorted ranges [first1,last1) and
[first2,last2), into a new range beginning at result with all its elements
sorted.
Syntax: OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2, OutputIterator result);
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
vector<int> v(10);
sort (first,first+5);
sort (second,second+5);
merge (first,first+5,second,second+5,v.begin());
cout << "The resulting vector contains:";
for (std::vector<int>::iterator it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it; std::cout << '\n'; return 0; }
for_each
#include <iostream>
#include <algorithm>
using namespace std;
Syntax :
void in_to_cm(double); //declaration
int main() Function for_each (InputIterator
{ //array of inches values first, InputIterator last, Function
double inches[] = { 3.5, 6.2, 1.0, 12.75, fn);
4.33 };
//output as centimeters
for_each(inches, inches+5, in_to_cm); The for_each() algorithm
cout << endl; allows you to do something to
return 0; every item in a container. You
} write your own function to
void in_to_cm(double in) //convert and
determine what that
display as centimeters
{ “something” is. Your function
cout << (in * 2.54) << ‘ ‘; can’t change the elements in
} the container, but it can use or
The output looks like this: display their values.
8.89 15.748 2.54 32.385 10.9982}
11
Transform()
#include <iostream>
#include <algorithm> The transform() algorithm does something
using namespace std; to every item in a container, and places the
int main() resulting values in a different container (or
{ //array of inches values the same one).
double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; Again, a user-written function determines
double centi[5]; what will be done to each item. The return
double in_to_cm(double); //prototype type of this function must be the same as
//transform into array centi[] that of the destination container.
transform(inches, inches+5, centi, in_to_cm);
for(int j=0; j<5; j++) //display array centi[]
cout << centi[j] << ‘ ‘;
cout << endl; Syntax:
return 0; OutputIterator transform (InputIterator
} first1, InputIterator last1,
double in_to_cm(double in) //convert inches to
OutputIterator result, UnaryOperation
centimeters
{ op);
return (in * 2.54); //return result
}
Maps
• Map
– Stores (key, object) pairs
– Unimodal: duplicate keys not allowed
– AKA: table, associative array
The STL Map Template
• map()
• map(const key_compare& comp)
• pair<iterator, bool> insert(const value_type&
x)
– Inserts x into the map
• iterator insert(iterator pos, const value_type&
x)
– Inserts x into the map, using pos as a hint to where it will be
inserted
• void insert(iterator, iterator)
– Inserts a range into the map
STL Map Template
• void erase(iterator pos)
– Erases the element pointed to by pos
• size_type erase(const key_type& k)
– Erases the element whose key is k
• void erase(iterator first, iterator last)
– Erases all elements in a range
• iterator find(const key_type& k)
– Finds an element whose key is k.
• data_type& operator[](const key_type& k)
– Returns a reference to the object that is associated
with a particular key.
– If the map does not already contain such an
object, operator[] inserts the default object
data_type()
Map Usage Example
int main ()
{ m.at(1) = “abc"; // changes the value
associated with key 5
map<int,string> m;
m[6] = “XYZ"; // changes the value
m.insert(pair<int,string>(5,"ABCD"));
associated with key 6
m.insert(pair<int,string>(6,"EFGH"));
cout<<m.at(5)<<endl;
m.insert(pair<int,string>(7,"IJKL"));
cout << m.at(5)<<endl ;
cout << m.at(6) <<endl;
cout << m.at(6) <<endl;
// prints value associated with key
5,6
}
begin() end()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 }; Output:
// Declaring iterator to a vector
The vector elements are : 1 2 3 4 5
vector<int>::iterator ptr;
return 0;
}
advance() :- This function is used to increment the iterator position till the specified number mentioned in its
arguments.
return 0;
}
Operations of iterators
next() prev()
This function returns the new This function returns the new
iterator that the iterator would iterator that the iterator would
point after advancing the point after decrementing the
positions mentioned in its positions mentioned in its
arguments. arguments.
// C++ code to demonstrate the working of next() and prev()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
return 0;
}
inserter() :- This function is used to insert the elements at any position in the container. It accepts 2
arguments, the container and iterator to position where the elements have to be inserted.
// C++ code to demonstrate the working of inserter()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
vector<int> ar1 = {10, 20, 30};
return 0;
}
Topic : STL Algorithm
Function Objects
STL has four
components
• STL has an ocean of algorithms, for all < algorithm > library functions
• Some of the most used algorithms on vectors and most useful one’s in
Competitive Programming are mentioned as follows :
– sort(first_iterator, last_iterator) – To sort the given vector.
– reverse(first_iterator, last_iterator) – To reverse a vector.
– *max_element (first_iterator, last_iterator) – To find the maximum element of a vector.
– *min_element (first_iterator, last_iterator) – To find the minimum element of a vector.
– accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of
vector elements
// Reversing the Vector
// A C++ program to demonstrate working of sort(), reverse() reverse(vect.begin(), vect.end());
#include <algorithm>
#include <iostream> cout << "\nVector after reversing is: ";
#include <vector> for (int i=0; i<6; i++)
#include <numeric> //For accumulate operation cout << vect[i] << " ";
using namespace std;
cout << "\nMaximum element of vector is: ";
int main() cout << *max_element(vect.begin(), vect.end());
{
// Initializing vector with array values cout << "\nMinimum element of vector is: ";
int arr[] = {10, 20, 5, 23 ,42 , 15}; cout << *min_element(vect.begin(), vect.end());
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect(arr, arr+n); // Starting the summation from 0
cout << "\nThe summation of vector elements is: ";
cout << "Vector is: "; cout << accumulate(vect.begin(), vect.end(), 0);
for (int i=0; i<n; i++)
cout << vect[i] << " "; return 0;
}
// Sorting the Vector in Ascending order
sort(vect.begin(), vect.end());
int main()
{
// Initializing vector with array values
int arr[] = {10, 20, 5, 23 ,42, 20, 15};
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect(arr, arr+n);
Output:
cout << "Occurrences of 20 in vector : "; Occurrences of 20 in vector: 2
// Counts the occurrences of 20 from 1st to Element found
// last element
cout << count(vect.begin(), vect.end(), 20);
return 0;
}
merge() in C++ STL
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initializing 1st container
vector<int> arr1 = { 1, 4, 6, 3, 2 };
Output:
// initializing 2nd container
vector<int> arr2 = { 6, 2, 5, 7, 1 }; The container after merging initial containers
is : 1 1 2 2 3 4 5 6 6 7
// declaring resultant container
vector<int> arr3(10);
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]); Output:
2 3 4 5 6
// Apply increment to all elements of
// arr[] and store the modified elements
// back in arr[]
transform(arr, arr+n, arr, increment);
return 0;
}