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()
Returns a Returns a
Returns a reverse iterator Returns a
Returns an reverse iterator Returns a constant reverse 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 (considered as moves from last
to first element vector. to first element (considered as
reverse end) reverse end)
The iterator functions in vectors handle the data inside the vector, not the index of the elements directly.
If you specifically need the index of elements, you can use a traditional loop with an index variable
// 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 Returns a Returns a pointer to the
Returns a memory array
reference to the reference to the reference to the reference to the
element at element at last element in used internally by
first element in the vector to store
position ‘g’ in the position ‘g’ in the the vector
the vector its owned
vector vector
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 insert a new
It assigns new It inserts new remove swap the It is used to It extends the element into
It is used to elements elements from contents of one the vector
value to the It pushes the pop or remove remove all the container by
vector elements into a before the a container vector with elements of the inserting new container, the
elements from element at the from the another vector new element is
elements by vector from the a vector from vector element at
replacing old back specified specified of same type. container position added to the
the back. position position or Sizes may end of the
ones
range. differ. 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
returns an iterator pointing to the which points to the theoretical
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 to the end of the list. the list i.e reversed the first element in
element of the list. beginning of the beginning of the
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 list
of elements a list elements from the new element is 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
Returns a constant iterator
Inserts an pointing to the
Returns a reverse iterator Returns the
element. And first element of
reverse iterator which points to maximum Assign values to
returns an the container, Function which
which points to the position number of the same or
iterator that that is, the changes the size
the last element before the elements that a different deque
points to the first iterator cannot of the deque.
of the deque beginning of the deque container container.
of the newly be used to
(i.e., its reverse deque (which is can hold.
inserted modify, only
beginning). considered its
elements. 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()
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
Returns a
Adds the element Deletes the top
Returns whether Returns the size of reference to the
‘g’ at the top of the most element of
the stack is empty the stack top most element
stack the stack
of the 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
7
Algorithms : Search Example 1
#include<iostream>
#include<algorithm> if (i != v1.end()) {
#include<vector> cout << "Sequence found at position: "
using namespace std; << distance(v1.begin(), i) << endl;
} else {
cout << "Sequence not found in v1" <<
int main() endl;
{ }
int inputs1[] = { 1,2,3,4,5,6,7,8};
int inputs2[] = { 2,3,4}; j = search(v1.begin() + 2, v1.end(), v2.begin
(), v2.end());
vector<int> v1(inputs1, inputs1+9);
vector<int> v2(inputs2, inputs2+3); // Output the result
if (j != v1.end()) {
vector<int>::iterator i ,j; cout << "Sequence found at position: "
<< distance(v1.begin(), j) << endl;
i = search(v1.begin(), v1.end(), v2.begin(), v2.end()); } else {
cout << "Sequence not found in v1 from
position 2 onwards" << endl;
/* now i points to the second element in v1 */ }
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 };
v1.push_back(8); sort(s,s+4,compare_string);
/* 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> The resulting vector contains: 5 10 10 15 20 20 25 30 40 50
using namespace std; Press any key to continue . . .
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
The output looks like this: or 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
centimeters
OutputIterator result, UnaryOperation
{ 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
#include <iostream>
#include<iterator>
#include <map>
#include <algorithm>
#include<cstring>
using namespace std;
map<const char*, int> months;
map<const char*, int>::iterator cur;
int main() {
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
cout << "june: " << months["june"] << endl;
cur = months.find("june"); first=key
second=value
cout << "Month " << cur->first<< ":" << cur->second << endl;
}
Example Maps
#include <iostream>
#include <map>
int main ()
{
map<int,string> m;
m.insert(pair<int,string>(5,"ABCD"));
m.insert(pair<int,string>(6,"EFGH"));
m.insert(pair<int,string>(7,"IJKL"));
cout << m.at(5)<<endl ;
cout << m.at(6) <<endl;
// prints value associated with key
5,6
/* note that the parameters in the above at() are the keys not the index */
}
Multi Set Example
#include<iostream>
#include <set>
using namespace std;
int main()
{
// multiset declare
multiset<int> s;
// Elements added to set
s.insert(12);
s.insert(10);
s.insert(2);
s.insert(10); // duplicate added
s.insert(90);
s.insert(85);
s.insert(75);
s.insert(90);
s.insert(95);
s.insert(45);
s.insert(80);
s.insert(45);
// Iterator declared to traverse
// set elements
Function Objects
• Functors (Function Objects or Functionals) are simply put object + ().
• In other words, a functor is any object that can be used with () in the
manner of a function.
• This includes normal functions, pointers to functions, and class objects
for which the () operator (function call operator) is overloaded, i.e.,
classes for which the function operator()() is defined.
• Sometimes we can use a function object when an ordinary function
won't work. The STL often uses function objects and provides several
function objects that are very helpful.
• Function objects are another example of the power of generic
programming and the concept of pure abstraction. We could say that
anything that behaves like a function is a function. So, if we define an
object that behaves as a function, it can be used as a function.
Function Objects
#include <iostream>
#include<vector>>
#include <algorithm>
using namespace std; function in class
class InCm {
public: obj of class to access function
void operator()(double in) use that obj as parameter
{
cout << (in * 2.54) << " ";
}
};
int main()
{
vector<double> inches;
inches.push_back(3.5);
inches.push_back(7);
InCm in_to_cm;
for_each (inches.begin(), inches.end(), in_to_cm);
cout << endl;
return 0;
}
Advantages of function object
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()
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
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);
}
// A C++ program uses transform() in STL to add 1 to all elements of arr[]
#include <bits/stdc++.h>
using namespace std;
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;
}