21CSC101T - Oodp Unit 5
21CSC101T - Oodp Unit 5
UNIT 5
STL – STANDARD TEMPLATE LIBRARY
• STL is an acronym for standard template library. It is a set of C++
template classes that provide generic classes and functions that can be
used to implement data structures and algorithms .STL is mainly
composed of :
1. Algorithms
2. Containers
3. Iterators
• STL provides numerous containers and algorithms which are very useful in
completive programming , for example you can very easily define a linked list in a
single statement by using list container of container library in STL , saving your
time and effort.
• STL is a generic library , i.e a same container or algorithm can be operated on any
data types , you don’t have to define the same algorithm for different type of
elements.
• For example , sort algorithm will sort the elements in the given range irrespective of
their data type , we don’t have to implement different sort algorithm for different
datatypes.
Use and Applications of STL
• STL being generic library provide containers and algorithms which can be used to
store and manipulate different types of data thus it saves us from defining these data
structures and algorithms from the scratch.
• Because of STL, now we do not have to define our sort function every time we make
a new program or define same function twice for the different data types, instead we
can just use the generic container and algorithms in STL.
• This saves a lot of time, code and effort during programming, thus STL is heavily
used in the competitive programming, plus it is reliable and fast.
Containers in STL
• Container library in STL provide containers that are used to create data structures
like arrays, linked list, trees etc.
• These container are generic, they can hold elements of any data types, for
example: vector can be used for creating dynamic arrays of char, integer, float and
other types.
Algorithms in STL
• STL provide number of algorithms that can be used of any container, irrespective
of their type. Algorithms library contains built in functions that performs complex
algorithms on the data structures.
• For example: one can reverse a range with reverse() function, sort a range
with sort() function, search in a range with binary_search() and so on.
• Algorithm library provides abstraction, i.e you don't necessarily need to know how
the the algorithm works.
Iterators in STL
• Iterators in STL are used to point to the containers. Iterators actually acts as a bridge
between containers and algorithms.
• For example: sort() algorithm have two parameters, starting iterator and ending
iterator, now sort() compare the elements pointed by each of these iterators and
arrange them in sorted order, thus it does not matter what is the type of the container
and same sort() can be used on different types of containers.
CONTAINERS
• Containers Library in STL gives us the Containers, which in simplest words, can be
described as the objects used to contain data or rather collection of object. Containers
help us to implement and replicate simple and complex data structures very easily
like arrays, list, trees, associative arrays and many more.
• The containers are implemented as generic class templates, means that a container
can be used to hold different kind of objects and they are dynamic in nature!
TYPES OF CONTAINERS
• Vector
• Deque
• List
• Array
• Stack (CONTAINER ADOPTER)
ASSOCIATIVE CONTAINERS
• MAP
• MULTIMAP
ALGORITHMS
• Find()
• Count()
• Sort()
• Search()
• Merge()
• For_each()
• Transform()
Array container
Syntax
for(int i: arr)
cout<<arr[i]<<" ";
return 0;
}
Output
11111
#include <iostream>
#include <array>
using namespace std;
int main() {
array <int , 10> arr;
cout<<arr.size()<<'\n'; // total num of indexes Example array:
size( ) or max_size( ) and sizeof( ) function: Both size( ) or max_size( ) are used to get the maximum
cout<<arr.max_size()<<'\n'; // total num of indexes number of indexes in the array while sizeof( ) is used to get the total size of array in bytes.
• push_back function:
insert(itr, element) method inserts the element in vector before the position pointed by
iterator itr.
• pop_back function
pop_back() is used to remove the last element from the vector. It reduces the size of
the vector by one.
Example: vector
#include <iostream> cout << "\nUpdated Vector: ";
#include <vector>
using namespace std; for (const int& i : num) {
int main() { cout << i << " ";
vector<int> num {1, 2, 3, 4, 5}; }
cout << "Initial Vector: ";
for (const int& i : num) { return 0;
cout << i << " "; }
}
Returns a Returns a
Returns a Returns a
reverse iterator Returns a constant reverse
Returns an reverse iterator constant reverse
pointing to the constant iterator iterator pointing
Returns an iterator pointing pointing to the iterator pointing
theoretical Returns a pointing to the to the theoretical
iterator pointing to the theoretical last element in to the last
element constant iterator theoretical element
to the first element that the vector element in the
preceding the pointing to the element that preceding the
element in the follows the last (reverse vector (reverse
first element in first element in follows the last first element in
vector element in the beginning). It beginning). It
the vector the vector. element in the the vector
vector moves from last moves from last
(considered as vector. (considered as
to first element to first element
reverse end) reverse end)
// C++ program to illustrate the iterators in vector
#include <iostream>
#include <vector>
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
at(g) front() back() data()
operator [g]
Returns a direct
Returns a reference Returns a reference Returns a pointer to the
Returns a reference
to the element at to the element at reference to the first memory array used
to the last element
position ‘g’ in the position ‘g’ in the element in the internally by the
in the vector
vector vector vector vector to store its
owned elements.
// C++ program to illustrate the element accesser in vector
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> g1;
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
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int main()
{
// Assign vector
vector<int> v;
// fill the vector with 10 five times
v.assign(5, 10);
cout << "The vector elements are: ";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
// inserts 15 to the last position
v.push_back(15);
int n = v.size();
cout << "\nThe last element is: " << v[n - 1];
// removes last element
v.pop_back();
// prints the vector
cout << "\nThe vector elements are: ";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
Syntax:
• list <data-type> name_of_list;
Functions associated with the Lists
returns a constant
end() function returns a constant
returns a reverse returns a constant reverse iterator
returns an iterator reverse iterator
begin() function returns a reverse iterator which random access returns a constant which points to the
pointing to the which points to the
returns an iterator iterator which points to the iterator which random access iterator theoretical element
theoretical last last element of the
pointing to the first points to the last position before the points to the which points to the preceding the first
element which end of the list. list i.e reversed
element of the list element of the list. beginning of the beginning of the element in the list
follows the last beginning of
list. list. i.e. the reverse end
element. container.
of the list.
Functions associated with the Lists
Returns the number of Used to resize a list Sorts the list in increasing
Reverses the list.
elements in the list. container. order.
Functions
max_size() associated
unique() withemplace_front()
the Lists emplace_back() clear()
function is used to
function is used to
Removes all insert a new element function is used to
Returns the insert a new element
duplicate into the list remove all the
maximum number of into the list
consecutive container, the new elements of the list
elements a list container, the new
elements from the element is added to container, thus
container can hold. element is added to
list. the beginning of the making it size 0.
the end of the list.
list.
Functions
operator= associated
swap() with the
splice()Lists merge() emplace()
Time Complexity : Time Complexity : Time Complexity : Time Complexity : Time Complexity :
O(1) O(1) O(1) O(1) O(1)
#include <iostream> cout << "The stack is : ";
#include <stack> showstack(s);
using namespace std;
void showstack(stack <int> s) cout << "\ns.size() : " << s.size();
{ cout << "\ns.top() : " << s.top();
while (!s.empty())
{
cout << '\t' << s.top(); cout << "\ns.pop() : ";
s.pop(); s.pop();
} showstack(s);
cout << '\n';
} return 0;
int main () }
{
stack <int> s;
s.push(10);
s.push(30);
s.push(20);
s.push(5);
s.push(1); Output:
The stack is : 1 5 20 30 10
s.size() : 5
s.top() : 1
s.pop() : 5 20 30 10
Deque
• Double ended queues are sequence containers with the feature of expansion and contraction on both
the ends.
• They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike
vectors, contiguous storage allocation may not be guaranteed.
• Double Ended Queues are basically an implementation of the data structure double ended queue. A
queue data structure allows insertion only at the end and deletion from the front.
• This is like a queue in real life, wherein people are removed from the front and added at the back.
Double ended queues are a special case of queues where insertion and deletion operations are
possible at both the ends.
• The functions for deque are same as vector, with an addition of push and pop operations for both front
and back.
Methods of Deque
• Returns a
• Returns a
• Returns a reverse constant iterator
• Inserts an reverse iterator • Returns the
iterator which pointing to the first
element. And which points to the • Assign values to • Function which
points to the last element of the maximum number
returns an iterator position before the the same or changes the size
element of the container, that is, of elements that a
that points to the beginning of the different deque of the deque.
deque (i.e., its the iterator cannot deque container
first of the newly deque (which is container.
reverse be used to modify, can hold.
inserted elements. considered its
beginning). only traverse the
reverse end). deque.
#include <iostream> cout << "\n quiz.size() : " << quiz.size();
#include <deque> cout << "\n quiz.max_size() : " << quiz.max_size();
using namespace std;
cout << "\n quiz.at(2) : " << quiz.at(2);
void showdq(deque <int> g) cout << "\n quiz.front() : " << quiz.front();
{ cout << "\n quiz.back() : " << quiz.back();
deque <int> :: iterator it;
for (it = g.begin(); it != g.end(); ++it) cout << "\n quiz.pop_front() : ";
cout << '\t' << *it; quiz.pop_front();
cout << '\n'; showdq(quiz);
}
cout << "\n quiz.pop_back() : ";
int main() quiz.pop_back();
{ showdq(quiz);
deque <int> quiz; return 0;
quiz.push_back(10); }
OUTPUT:
quiz.push_front(20);
quiz.push_back(30); The deque quiz is : 15 20 10 30
quiz.size() : 4
quiz.push_front(15); quiz.max_size() : 4611686018427387903
cout << "The deque quiz is : "; quiz.at(2) : 10
quiz.front() : 15
showdq(quiz); quiz.back() : 30
quiz.pop_front() : 20 10 30
quiz.pop_back() : 20 10
Methods of Deque
• push_front() • push_back() • pop_front() • pop_back() • front() • back() • clear() • erase() • empty() • size()
• Multimap is similar to map with an addition that multiple elements can have
same keys. Rather than each element being unique, the key value and
mapped value pair has to be unique in this case.
Basic functions associated with multiMap
• pair<int,int>
• begin() • end() • size() • max_size() • empty() insert(keyvalue,multim
apvalue
• Returns an iterator to
• Returns an iterator to • Returns the number of • Returns the maximum
the theoretical element • Returns whether the • Adds a new element to
the first element in the elements in the number of elements that
that follows last element multimap is empty the multimap
multimap multimap the multimap can hold
in the multimap
#include <iostream>
#include <map>
#include <iterator> // remove all elements up to element with value 30 in gquiz2
• Iterators can be used to traverse the container, and we can use the iterator to get the value
of the element it is pointing to.
• Are used to point at the memory addresses of STL containers.
• They are primarily used in sequence of numbers, characters etc.
• They reduce the complexity and execution time of program
• Syntax: container<datatype>::iterator iteratorname;
OPERATIONS ON ITERATORS
• begin() Operation
• end() Operation
• prev() Operation
It will return the nth predecessor to i, i.e iterator pointing to the nth predecessor element from
the element pointed by i.
SYNTAX: prev(iterator i, int n)
Example iterators
advance() :- This function is used
to increment the iterator position till the
// C++ code to demonstrate the working of advance() specified number mentioned in its arguments.
#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;
}
// 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 };
// Declaring iterators to a vector
vector<int>::iterator ptr = ar.begin();
// Using next() to return new iterator
Output:
// points to 4
The position of new iterator using next() is : 4
auto it = next(ptr, 3);
The position of new iterator using prev() is : 2
// Using prev() to return new iterator
// points to 2
auto it1 = prev(ptr, 3);
// Displaying iterator position
cout << "The position of new iterator using next() is : ";
cout << *it << " ";
cout << endl;
// Displaying iterator position
cout << "The position of new iterator using prev() is : ";
cout << *it1 << " ";
cout << endl;
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.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> d{100, 200, 300};
std::vector<int> v{1, 2, 3, 4, 5};
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
}
ALGORITHMS
• 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.
#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);
#include <vector>
#include <algorithm>
int print_even(int n) {
if (n % 2 == 0)
return 0;
}
Transform() algorithm
The transform function is present in the C++ STL. To use it, we have to include the algorithm header file.
This is used to perform an operation on all elements. For an example if we want to perform square of each
element of an array, and store it into other, then we can use the transform() function.
Syntax:
return 0;
}
Binary Operation Mode
In this mode the it can perform binary operation on the given data. If we want to
add elements of two different array, then we have to use binary operator mode.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3, 4, 5};
int res[5];
transform(arr1, arr1+5, arr2,res,multiply);
return 0;
}