Session #2 ( STL's )

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

STL’S

Presented By : Mazen Othman


● Problem Solving Instructor
‫‪Agenda‬‬

‫● رﺑﻨﺎ ﯾﺴﺎﻣﺤﻚ ﯾﺎﻟﻲ ﻣﺴﮭﺮﻧﻲ‬


Intro To STL’s
What Is STL’s ?

● The Standard Template Library (STL) is a set of C++ template classes to


provide common programming data structures and functions such as lists,
stacks, arrays, etc. It is a library of container classes, algorithms, and
iterators. It is a generalized library and so, its components are parameterized.

● The C++ Standard Template Library (STL) is a collection of algorithms, data


structures, and other components that can be used to simplify the
development of C++ programs.
Containers

A container is a holder object that stores a collection of other objects (its elements).
They are implemented as class templates, which allows great flexibility in the types
supported as elements.
The container manages the storage space for its elements and provides member
functions to access them, either directly or through iterators
Itrators → ( reference objects with similar properties to pointers ).
Containers
Types Containers

1. Sequence containers
2. Associative containers
3. Unordered associative containers → ( Search With Yourself )
4. Container adapters
Sequence containers
Sequence containers implement data structures that can be accessed sequentially.

● Array : Static contiguous array

● Vector : Dynamic contiguous array

● Deque : Double-ended queue

● Forward_list : Singly-linked list

● List : Doubly-linked list


Associative containers

Associative containers implement sorted data structures that can be quickly searched
( O ( log n ) complexity → ( BST Algorithm )

● Set : Collection of unique keys, sorted by keys

● Map : Collection of key-value pairs, sorted by keys, keys are unique

● Multiset : Collection of keys, sorted by keys

● Multimap : Collection of key-value pairs, sorted by keys


Unordered associative containers ( Not in Scope )
Unordered associative containers implement unsorted (hashed)
data structures that can be quickly searched
( O ( 1 ) amortized, O ( n ) worst-case complexity ) → ( Hash Table Algorithm )

● Unordered_set : Collection of unique keys, hashed by keys.

● Unordered_map : Collection of key-value pairs, hashed by keys, keys are unique.

● Unordered_multiset : Collection of keys, hashed by keys

● Unordered_multimap : Collection of key-value pairs, hashed by keys


Container adapters

Container adapters provide a different interface for sequential containers.

● Stack : Adapts a container to provide stack ( LIFO data structure ) → ( Last In First Out )

● Queue : Adapts a container to provide queue ( FIFO data structure ) → ( First In First Out )

● Priority_queue : Adapts a container to provide priority queue .


Vector
● Vectors vs arrays
● Why vector ?
Vector
● How to initialize vector ?
● How to use its functionalities
Vector
Built-in Functions

● front()
● back()
● size()
● empty()
● insert()
● erase()
● push_back()
● pop_back()
Note That Vectors allow random access just like normal arrays
● sort() v[0], v[1], v[2], …... , v[v.size()-1]
Let’s Practice
Problem 1

You are given Q queries.


Each query is a command starting with ‘a’ , ‘p’ or ‘d’.
‘a’ you will be given an integer N and you have to add N
to your vector.
‘d’ you have to delete the last element.
‘p’ print the current vector elements.
Solution
Problem 1
Iterator
Iterators are used to point at the memory addresses of STL containers. They are
primarily used in sequences of numbers, characters etc. They reduce the
complexity and execution time of the program.
Read More About Itrators → ( Introduction To Iterator ) # Very Important Article
● How To Declare An Iterator :
Operations of iterators :-
1. begin() :- This function is used to return the beginning position
of the container.
2. end() :- This function is used to return the after end position of
the container.
auto
The auto keyword in C++ automatically detects and assigns a data type to the variable
with which it is used. The compiler analyses the variable's data type by looking at its
initialization. It is necessary to initialize the variable when declaring it using the auto
keyword.
Read More About Type Interface→ ( Type Interface )
● How To initialize an iterator with auto :
Important Note :-
The variable declared with auto keyword
should be initialized at the time of its
declaration only or else there will be a
compile-time error.
Print Methods
Pair
● Why pairs ?
● Pair initialization
Let’s Practice
Problem 2

Mario has N college friends and he wants to


store their names and grades. He is a lazy
boy so he asked you to help him.
Solution
Problem 2
Stack
Last In First Out

● .push()
adds an element to the top of the stack.
● .pop()
removes the top element.
Important To Know That We Cannot
Access Any Element at The Middle
Stack

.top()
returns the top element.
.size()
Returns the number of elements.
.empty()
returns whether the stack is empty.
Stack
Stack Declaration Example

What Is OutPut
Brainstorm With Me !

What Is OutPut
Answer
Let’s Practice
Problem 3

Koko will be given a sequence of brackets


‘{‘, ‘}’. His task is to check whether this
sequence results a regular brackets
sequence or not, "{}", "{{}}" are regular
bracket sequences while "{{", "{}{", are not.
print yes if it's a regular bracket sequence
otherwise print no.
Solution
Problem 3
Queue
First In First Out

.Pop() = dequeue Remove from front


.push() = enqueue Insert into back
Queue
First In First Out

Important To Know That We Cannot


Access Any Element at The Middle
Queue

.front()
Return Front element
.back()
Return rear element
.size()
Returns the number of elements.
.empty()
returns whether the queue is empty.
Brainstorm With Me !

What Is OutPut
Let’s Practice
Problem 4
Qotb ranks students according to their intelligence. N
students will enter the magical bus in a queue, but the
queue to bus has some magical rules, when one student
come in the back of the queue the mentors check
whether the first one in the queue has the same rank of
him or no, if the last rank matches the first one, the first
one will enter the bus. ranks of students according to
Koko are "smart", "geek", and "nerd", you should print the
ranks of the students that will stand in the queue from
the beginning to the end after that the N students came to
stand in the queue.
Solution
Problem 4
Queue Vs Stack
Deque
Deque can insert and delete from both ends

Deque Declaration
Deque
.push_back()
Push element to the back of deque.
.push_front()
Push element to the front of deque.
.pop_back()
Pop element from the back of deque.
.pop_front()
Pop element from the front of deque.

What Is OutPut
Deque

.size()
Return the size of deque.
.empty()
Return a bool, true if deque is
empty and false otherwise.
.clear()
Remove all the elements from
deque.
What Is OutPut
Let’s Practice
Problem 5

Given Q queries of three types.


x = 1 means add y to the end of the list.
x = 2 means add y to the start of the list.
- 3 means to delete the smallest of the first vs the last
number in the list.
Print the size of the list and its elements after all the queries.
Solution
Problem 5
Priority Queue
● Sorted Data Structure
Priority queue stores the elements in
a way that makes the top element Is the biggest one.

Important To Know That Using this declaration priority queue Will store the elements in a way
that makes the top element is the smallest one.
Priority Queue

.push()
Add an element to the priority queue.
.top()
Get top element of the priority queue.
.pop()
Remove top element of the priority
queue.

What Is OutPut
Let’s Practice
Problem 6
Thousands of years ago, a pharaoh has got new words as a
present, since you
are the smartest engineer in the country, he immediately asked
for you to help him, he will give you the words one by one and
you should put them in a book
( he give you the word when he tell you the secret number 1 ),
easy task right ?. unfortunately the pharaoh wants to test your
focus level during the job, so from time to time he will ask you to
tell him which word is lexicographically the biggest among all
the words he gave you until the moment he asked you in when
he miss the secret number .
Solution
Problem 6
Binary Search Tree ( BST ) - [ Just Brief ]
What is BST ?
● Algorithm to search for a key in a given Binary Search Tree:
● Let’s say we want to search for the number X, We start at the
root. Then:
● We compare the value to be searched with the value of the root.
● If it’s equal we are done with the search if it’s smaller we know
that we need to go to the left subtree because in a binary search
tree all the elements in the left subtree are smaller and all the
elements in the right subtree are larger.
● Repeat the above step till no more traversal is possible
● If at any iteration, key is found, return True. Else False.
Set
● Sorted Data Structure & Does Not Repeated Values
Set can sort in both orders, Ascending and descending.
● Increase Set
.insert () : to add element in the set.
Insertion takes O ( log ( n ) ). → ( Because its built with BST Algorithm )

● Decrease Set
Remember That ( Iterator )
● To access set elements, you need an iterator.
● An iterator is an object that points/refers to an element of a sequence.
● The end of the sequence is one past the last element.
● * → To Show element
● & → To Show Reference || Address
Let’s Practice
Problem 7
Fred sent his daughter to the shop to buy some
groceries, but he gave her a very weird shopping list,
she found that many items in this list are repeated.
She wants you to help him create a new list, where
each item is unique.
Solution
Problem 7
MultiSet
● Sorted Data Structure & Can Repeat Values and Count Them
MultiSet can sort in both orders, Ascending and descending.

● Increase MultiSet

● Decrease MultiSet
MultiSet

.count(): return frequency of an element x in the Multiset.


.erase():
remove all elements up to element with value x
remove all elements with value x

● .insert() : to add element in the multiset. Insertion takes O ( log ( n ) ).


● Determine the elements in the multiset after running this code
MultiSet

What Is OutPut
Map
● You can use any data type for the key or value.

● Declare Map
Map
● Assign a value to the key. ● .size() : shows how many elements in the map.
● To show the value of a certain key. ● .clear() : clear all elements in the map
Let’s Practice
Problem 8
Fred is the judge of a tennis tournament. He was a
given a list of n names, the names of the players who
won a match. The player who won the greatest number
of matches wins the whole tournament. Print the name
of the player who won the tournament, and how many
times Zeyad won matches.
Solution
Problem 8
Zeyad Not Equal zeyad , This Your Fault Right ?
InCase Not Shater

To traverse on the map, you have to use iterators.


map < key , value > :: iterator iterator_name ;
Algorithms
○ Some Functions ○ Some Functions
■ Max_element () ■ Nth_element ()
■ Min_element () ■ Is_sorted ()
■ Accumulate () ■ Sort ()
■ Count () ■ Reverse ()
■ Find () ■ Next_permutation ()
■ Binary_search ()
■ Lower_bound ()
■ Upper_bound ()
■ Erase ()
■ Unique ()
Max_element ()

returns max element in range


Complexity : O ( N )

OutPut
Min_element ()

returns min element in range


Complexity : O ( N )

OutPut
Accumulate ()

return sum all the numbers in range


Complexity : O ( N )

OutPut
Count ()

count all the occurrences in range


Complexity : O ( N )

OutPut
Find ()

finds a certain element and returns iterator point to its position


Complexity : O ( N )

OutPut
Binary Search ()
Search if the element is found return 1. Otherwise, returns 0
( Note That Elements must be sorted )
Complexity : O ( Log 2 ( n ) )

OutPut
Lower_Bound ()
returns first number bigger than or equal to x
( Note That Elements must be sorted )
Complexity : O ( Log 2 ( n ) )

OutPut
Upper_Bound ()
returns first number bigger than x
( Note That Elements must be sorted )
Complexity : O ( Log 2 ( n ) )

OutPut
Erase ()

given an iterator, it removes this value and resize the vector


Complexity : O ( N )

OutPut
Nth_element ()

NOT SORTING. Puts all the elements less than n behind and all the elements bigger after.
Complexity : O ( N Log ( N ) )

OutPut
Is_sorted ()

returns True or False Based on The Elements is Sorted or not


Complexity : O ( N log ( N ) )

OutPut
Sort ()

Sort The Element Ascending


Complexity : O ( N log ( N ) )

OutPut
Reverse ()

Reverse The Elements Sort


Complexity : O ( N )

OutPut
Next_permutation ()

gets the next permutation


Complexity : O ( N ^ 2 )

OutPut
Task Question

● What Is Difference Between Pointer And Iterator ?


Any Questions
Thank You

You might also like