0% found this document useful (0 votes)
20 views76 pages

21CSC101T - Oodp Unit 5

oodp unit 5 lecture notes

Uploaded by

pd0096
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views76 pages

21CSC101T - Oodp Unit 5

oodp unit 5 lecture notes

Uploaded by

pd0096
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

21CSC101T –OODP

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

Containers are classified into four categories :


• Sequence containers : Used to implement data structures that are sequential in
nature like arrays(array) and linked list(list).
• Associative containers : Used to implement sorted data structures such as map, set
etc.
• Unordered associative containers : Used to implement unsorted data structures.
• Containers adaptors : Used to provide different interface to the sequence
containers.
SEQUENCE CONTAINERS

• Vector
• Deque
• List
• Array
• Stack (CONTAINER ADOPTER)
ASSOCIATIVE CONTAINERS

• MAP
• MULTIMAP
ALGORITHMS

• Find()
• Count()
• Sort()
• Search()
• Merge()
• For_each()
• Transform()
Array container

• Arrays are collection of homogenous objects or similar datatypes.


• Size of the array is static only .
• array container in STL provides us the implementation of static array.
• Include header file as #include <array>

Syntax

array<object_type, array_size> array_name;


#include <iostream>
#include <array>
using namespace std;
int main() { Example:
array <char , 3> arr={'G','f','G'}; array[ ] Operator : This is
cout<<arr[0] <<" "<<arr[2]; similar to the normal array, we
use it to access the element
return 0;
store at index ‘i’ .
}
Output
GG
Operations on array front() back()

This returns the This returns the


first element of last element of
array. array.
#include <iostream>
#include <array>
using namespace std;
int main() {
array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 Example array:
front( ) and back( ) function: These methods are used to access the first and
the last element of the array directly.

cout<<arr.front() <<" "<<arr.back();


return 0;
}
Output
71 71
#include <iostream>
#include <array>
using namespace std;
int main() {
array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71
array <int , 3> arr1={'M','M','P'}; // ASCII val of 'M' = 77 and
'P' = 80
Example array:
arr.swap(arr1); // now arr = {M,M,P} swap( ) function: This swap function is used to swap the content
of the two arrays.
cout<<arr.front() <<" "<<arr.back();
return 0;
}
Output
77 80
Operations on array
empty() fill()

This function returns true This function is used to


when the array size is fill the entire array with a
zero else returns false. particular value.
#include <iostream>
#include <array>
using namespace std;
int main() {
array <int , 5> arr; Example: array: fill( ) function: This is specially used to
initialize or fill all the indexes of the array with a similar
arr.fill(1); value.

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.

cout<<sizeof(arr); // total size of array


return 0;
}
Output
10
10
40
Operations on array
at() get() operator[]

This function This is similar


This function This function is is not the to C-style
is used to also used to member of arrays. This
access the access the array class but method is also
elements of elements of overloaded used to access
array. array. function from array
class tuple. elements.
// // C++ code to demonstrate working of array, to() and get()
#include<iostream>
#include<array> // for array, at()
#include<tuple> // for get()
using namespace std;
int main()
{
// Initializing the array elements
array<int,6> ar = {1, 2, 3, 4, 5, 6};

// Printing array elements using at()


cout << "The array elements are (using at()) : ";
for ( int i=0; i<6; i++)
cout << ar.at(i) << " ";
cout << endl; Output:
The array elements are (using at()) : 1 2 3 4 5 6
// Printing array elements using get() The array elements are (using get()) : 1 2 3 4 5 6
cout << "The array elements are (using get()) : "; The array elements are (using operator[]) : 1 2 3 4 5 6
cout << get<0>(ar) << " " << get<1>(ar) << " ";
cout << get<2>(ar) << " " << get<3>(ar) << " ";
cout << get<4>(ar) << " " << get<5>(ar) << " ";
cout << endl;

// Printing array elements using operator[]


cout << "The array elements are (using operator[]) : ";
for ( int i=0; i<6; i++)
cout << ar[i] << " ";
cout << endl;
return 0;
}
Vector
• Vectors are used to store elements of similar data types. However, unlike arrays,
the size of a vector can grow dynamically.
• 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. And
include header file as #include <vector>
• Syntax: vector<data type> vector name;
MEMBER FUNCTIONS OF THE VECTOR

• push_back function:

Push_back() is used for inserting an element at the end of the vector.


• insert 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 << " "; }
}

// add the integers 6 and 7 to the vector


num.push_back(6);
num.push_back(7);
functions associated with the vector
Iterators
begin() end() rbegin() rend() cbegin() cend() crbegin() crend()

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>

using namespace std;

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

cout << "\nOutput of cbegin and cend: ";


for (auto i = g1.cbegin(); i != g1.cend(); ++i)
cout << *i << " ";

cout << "\nOutput of rbegin and rend: ";


for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << *ir << " ";

cout << "\nOutput of crbegin and crend : ";


for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir)
cout << *ir << " ";

return 0;
}
Functions associated with the vector

Capacity

size() max_size() capacity() resize(n) empty() shrink_to_fit() reserve()

Returns the size Reduces the


Returns the of the storage capacity of the Requests that the
Returns the Resizes the vector capacity be
maximum number space currently Returns whether container to fit its
number of container so that it at least enough to
of elements that allocated to the the container is size and destroys
elements in the contains ‘n’ contain n
the vector can vector expressed empty. all elements
vector. elements. elements.
hold. as number of beyond the
elements. capacity.
#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> g1;

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


g1.push_back(i);
Output:
cout << "Size : " << g1.size(); Size : 5
cout << "\nCapacity : " << g1.capacity(); Capacity : 5
cout << "\nMax_Size : " << g1.max_size();
Max_Size : 4611686018427387903
// resizes the vector size to 4 Size : 4
g1.resize(4); Vector is not empty
Vector elements are: 1 2 3 4
// prints the vector size after resize()
cout << "\nSize : " << g1.size();

// checks if the vector is empty or not


if (g1.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";
// Shrinks the vector
g1.shrink_to_fit();
cout << "\nVector elements are: ";
for (auto it = g1.begin(); it != g1.end(); it++)
cout << *it << " ";

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;

for (int i = 1; i <= 10; i++)


g1.push_back(i * 10); Output:
Reference operator [g] : g1[2] = 30
cout << "\nReference operator [g] : g1[2] = " << g1[2]; at : g1.at(4) = 50
front() : g1.front() = 10
cout << "\nat : g1.at(4) = " << g1.at(4); back() : g1.back() = 100
The first element is 10
cout << "\nfront() : g1.front() = " << g1.front();

cout << "\nback() : g1.back() = " << g1.back();

// pointer to the first element


int* pos = g1.data();

cout << "\nThe first element is " << *pos;


return 0;
}
Functions associated with the vector
Modifiers
assign() push_back() pop_back() insert() erase() swap() clear() emplace() emplace_back()

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

// inserts 5 at the beginning


v.insert(v.begin(), 5);
cout << "\nThe first element is: " << v[0];

// removes the first element


v.erase(v.begin());
cout << "\nThe first element is: " << v[0];
// inserts at the beginning
v.emplace(v.begin(), 5);
cout << "\nThe first element is: " << v[0];
// Inserts 20 at the end
v.emplace_back(20);
n = v.size();
cout << "\nThe last element is: " << v[n - 1];

// erases the vector


v.clear();
cout << "\nVector size after clear(): " << v.size();
// two vector to perform swap
vector<int> v1, v2;
v1.push_back(1);
v1.push_back(2);
v2.push_back(3);
v2.push_back(4);

cout << "\n\nVector 1: ";


for (int i = 0; i < v1.size(); i++)
cout << v1[i] << " ";

cout << "\nVector 2: ";


for (int i = 0; i < v2.size(); i++)
cout << v2[i] << " ";
// Swaps v1 and v2
v1.swap(v2);

cout << "\nAfter Swap \nVector 1: ";


for (int i = 0; i < v1.size(); i++)
cout << v1[i] << " ";

cout << "\nVector 2: ";


for (int i = 0; i < v2.size(); i++)
cout << v2[i] << " ";
}
List

• Lists are sequence containers that allow non-contiguous memory allocation.


• As compared to vector, list has slow traversal, but once a position has been found, insertion and
deletion are quick.
• List types are : 1.singly linked list and 2.doubly linked list
• Include header file #include<list>

Syntax:
• list <data-type> name_of_list;
Functions associated with the Lists

• front() back() push_front(g) push_back(g) pop_front() pop_back()

Removes the first Removes the last


Adds a new element ‘g’
• Returns the value of the Returns the value of the Adds a new element ‘g’ element of the list, and element of the list, and
at the beginning of the
first element in the list. last element in the list . at the end of the list. reduces size of the list by reduces size of the list by
list .
1. 1
Functions associated with the Lists

begin() end() rbegin() rend() cbegin() cend() crbegin() crend()

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

empty() insert() erase() assign() remove()

Inserts new elements in Assigns new elements to


Removes a single Removes all the elements
Returns whether the list is the list before the list by replacing current
empty(1) or not(0). element or a range of from the list, which are
element at a specified elements and resizes the equal to given element.
elements from the list.
position. list.
Functions associated with the Lists

reverse() size() list resize() sort()

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

This operator is used


This function is
to assign new Used to transfer Extends list by
used to swap the
contents to the elements from one Merges two sorted inserting new
contents of one list
container by list to another. lists into one element at a given
with another list of
replacing the position.
same type and size.
existing contents.
#include <iostream>
#include <list>
#include <iterator>
using namespace std;
//function for printing the elements in a list
void showlist(list <int> g)
{
list <int> :: iterator it; The output of the above program is :
for(it = g.begin(); it != g.end(); ++it)
cout << '\t' << *it; List 1 (list1) is : 0 2 4 6 8 10 12 14 16 18
cout << '\n'; List 2 (list2) is : 27 24 21 18 15 12 9 6 3 0
} list1.front() : 0
int main() list1.back() : 18
{ list1.pop_front() : 2 4 6 8 10 12 14 16 18
list <int> list1, list2;
list2.pop_back() : 27 24 21 18 15 12 9 6 3
for (int i = 0; i < 10; ++i)
list1.reverse() : 18 16 14 12 10 8 6 4 2
{
list2.sort(): 3 6 9 12 15 18 21 24 27
list1.push_back(i * 2);
list2.push_front(i * 3);
}
cout << "\nList 1 (list1) is : ";
cout << "\nList 2 (list2) is : ";
showlist(list1);
showlist(list2);
cout << "\nlist1.front() : " << list1.front();
cout << "\nlist1.back() : " << list1.back();
cout << "\nlist1.pop_front() : ";
list1.pop_front(); The output of the above program is :
showlist(list1);
cout << "\nlist2.pop_back() : "; List 1 (list1) is : 0 2 4 6 8 10 12 14 16 18
list2.pop_back(); List 2 (list2) is : 27 24 21 18 15 12 9 6 3 0
showlist(list2); list1.front() : 0
cout << "\nlist1.reverse() : "; list1.back() : 18
list1.reverse(); list1.pop_front() : 2 4 6 8 10 12 14 16 18
showlist(list1); list2.pop_back() : 27 24 21 18 15 12 9 6 3
cout << "\nlist2.sort(): "; list1.reverse() : 18 16 14 12 10 8 6 4 2
list2.sort(); list2.sort(): 3 6 9 12 15 18 21 24 27
showlist(list2);
return 0;
}
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.
• OPERATIONS OF STACK:

1.Push() –insert the element in to the stack

2.Pop() – delete the element from the stack

Include header file as #include<stack>

Syntax: stack<datatype>object name


Functions associated with stack

empty() size() top() push(g) pop()

Returns a reference Adds the element ‘g’ Deletes the top


Returns whether Returns the size of
to the top most at the top of the most element of the
the stack is empty the stack
element of the stack stack stack

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

• deque insert() • rbegin() • rend() • cbegin() • max_size() • assign() • resize()

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

• Is used to • Is used to return


• Is used to remove
• This function is • This function is • Is used to pop • Is used to pop • Is used to • Is used to •Is used to check the size of the
remove all the elements from a
used to push used to push or remove or remove reference the reference the if the deque deque container
elements of the container from
elements into a elements into a elements from a elements from a first element of last element of container is or the number of
deque container, the specified
deque from the deque from the deque from the deque from the the deque the deque empty or not. elements in the
thus making its position or
front. back. front. back. container. container. deque container.
size 0. range.
MAP

• Maps are associative containers that store elements in a mapped fashion.


• Each element has a key value and a mapped value. No two mapped values can have same
key values.
• Include header file as #include<map>
• Syntax:

Map<datatype ,datatype>object name;


Map example
// Get an iterator pointing to the first element in the map
map<string, int>::iterator it = mp.begin();
#include <iostream>
#include <map> // Iterate through the map and print the elements
using namespace std; while (it != mp.end()) {
int main() cout << "Key: " << it->first
{ << ", Value: " << it->second << endl;
// Create a map of strings to integers ++it;
}
map<string, int> map1;
// Insert some values into the map Output:
map1["one"] = 1; Key: one, Value: 1
map1["two"] = 2; Key: two, Value: 2
map1["three"] = 3; Key: three, Value: 3
MULTIMAP

• 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

using namespace std;


cout << "\ngquiz2 after removal of elements less than key=3 : \n";
int main()
{ cout << "\tKEY\tELEMENT\n";
multimap <int, int> gquiz1; // empty multimap container gquiz2.erase(gquiz2.begin(), gquiz2.find(1,2));
// insert elements in random order for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr)
gquiz1.insert(pair <int, int> (1, 40)); {
gquiz1.insert(pair <int, int> (2, 30)); cout << '\t' << itr->first
gquiz1.insert(pair <int, int> (3, 60));
gquiz1.insert(pair <int, int> (4, 20));
<< '\t' << itr->second << '\n';
gquiz1.insert(pair <int, int> (5, 50)); }
gquiz1.insert(pair <int, int> (6, 50));
gquiz1.insert(pair <int, int> (6, 10)); // remove all elements with key = 4
int num;
// printing multimap gquiz1 num = gquiz2.erase(4);
multimap <int, int> :: iterator itr;
cout << "\nThe multimap gquiz1 is : \n";
cout << "\ngquiz2.erase(4) : ";
cout << "\tKEY\tELEMENT\n"; cout << num << " removed \n" ;
for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) cout << "\tKEY\tELEMENT\n";
{ for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr)
cout << '\t' << itr->first {
<< '\t' << itr->second << '\n'; cout << '\t' << itr->first
}
cout << endl;
<< '\t' << itr->second << '\n';
}
// assigning the elements from gquiz1 to gquiz2
multimap <int, int> gquiz2(gquiz1.begin(),gquiz1.end()); cout << endl;

// print all elements of the multimap gquiz2


cout << "\nThe multimap gquiz2 after assign from gquiz1 is : \n";
cout << "\tKEY\tELEMENT\n";
return 0;
for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr)
{ }
cout << '\t' << itr->first
<< '\t' << itr->second << '\n';
Output:
The multimap gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
4 20
5 50
6 50
6 10
The multimap gquiz2 after assign from gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
4 20
5 50
6 50
6 10
gquiz2 after removal of elements less than key=3 :
KEY ELEMENT
3 60
4 20
5 50
6 50
6 10
gquiz2.erase(4) : removed
KEY ELEMENT
3 60
5 50
6 50
6 10
ITERATORS

• 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

This method returns an iterator to the start of the given container.


SYNTAX: begin()

• end() Operation

This method returns an iterator to the end of the given container.


SYNTAX: end()
OPERATIONS ON ITERATORS
• next() Operation
It will return the nth iterator to i, i.e iterator pointing to the nth element from the element pointed
by i.
SYNTAX: next(iterator i ,int n)

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

// Declaring iterator to a vector


vector<int>::iterator ptr = ar.begin();

// Using advance() to increment iterator position Output:


// points to 4 The position of iterator after advancing is : 4
advance(ptr, 3);

// Displaying iterator position


cout << "The position of iterator after advancing is : ";
cout << *ptr << " ";

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

// when inserting in a sequence container, insertion point advances


// because each std::insert_iterator::operator= updates the target iterator
std::copy(d.begin(), d.end(), std::inserter(v, std::next(v.begin())));

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.

– 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
ALGORITHMS

• count(first_iterator, last_iterator,x) – To count the occurrences of x in vector.


• find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end())
if element is not present in vector.
• Merge() - useful to merge sort two containers into a single container.
// 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());
{
vector<int> vect(10,20,5,23,42,15); cout << "\nMinimum element of vector is: ";
cout << *min_element(vect.begin(), vect.end());
cout << "Vector is: ";
for (int i=0; i<n; i++) // Starting the summation from 0
cout << vect[i] << " "; cout << "\nThe summation of vector elements is: ";
cout << accumulate(vect.begin(), vect.end(), 0);
// Sorting the Vector in Ascending order
sort(vect.begin(), vect.end()); return 0;
}
cout << "\nVector after sorting is: ";
for (int i=0; i<n; i++)
cout << vect[i] << " ";
Output:
Vector before sorting is: 10 20 5 23 42 15 Vector after
sorting is: 5 10 15 20 23 42 Vector before reversing is: 5
10 15 20 23 42 Vector after reversing is: 42 23 20 15 10 5
Maximum element of vector is: 42
Minimum element of vector is: 5
The summation of vector elements is: 115
// C++ program to demonstrate working of count() and find() count(first_iterator, last_iterator,x) – To
#include <algorithm>
#include <iostream> count the occurrences of x in vector.
#include <vector>
using namespace std;
find(first_iterator, last_iterator, x) –
Points to last address of vector
int main()
{
((name_of_vector).end()) if element is not
vector<int> vect(10,20,6,23,5,42,20,15); present in vector.
cout << "Occurrences of 20 in vector : ";

// Counts the occurrences of 20 from 1st to


// last element
cout << count(vect.begin(), vect.end(), 20);

// find() returns iterator to last address if


// element not present
find(vect.begin(), vect.end(),5) != vect.end()?
cout << "\nElement found":
Output:
else Occurrences of 20 in vector: 2
cout << "\nElement not found"; Element found
return 0;
}
// C++ code to demonstrate the working of merge() implementation 1

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

// sorting initial containers


sort(arr1.begin(), arr1.end());
sort(arr2.begin(), arr2.end());

// using merge() to merge the initial containers


merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), arr3.begin());

// printing the resultant merged container


cout << "The container after merging initial containers is : ";

for (int i = 0; i < arr3.size(); i++)


cout << arr3[i] << " ";
return 0;
}
for_each algorithm
• This loop accepts a function which executes over each of the container elements.
• This loop is defined in the header file “algorithm”: #include<algorithm>.
• It is versatile, i.e. Can work with any container.
• It reduces chances of errors one can commit using generic for loop
• It makes code more readable
• for_each loops improve overall performance of code
• SYNTAX
• for_each (InputIterator start_iter, InputIterator last_iter, Function fnc)
#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int print_even(int n) {

if (n % 2 == 0)

cout << n << ' ';


Vector contains following even
}
number
int main(void) { 24
vector<int> v = {1, 2, 3, 4, 5};

cout << "Vector contains following even numebr" << endl;

for_each(v.begin(), v.end(), print_even);

cout << endl;

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:

transform(input , array size , output, function);

The transform function works in two modes. These modes are −

1.Unary operation mode

2.Binary operation mode


Unary Operation Mode
In this mode the function takes only
one operator (or function) and
convert into output.
#include <bits/stdc++.h>
using namespace std;

int square(int x) { return (x*x); }


int main()
{
int arr[] = {1, 2, 3, 4, 5};
transform(arr, arr+5, arr, square);

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


cout << arr[i] << " ";

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 multiply(int x,int y) { return (x*y); }

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

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


cout << res[i] << " ";

return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy