SlideShare a Scribd company logo
1 of 19
C++ STL
(quickest way to learn, even for absolute beginners)
C++ STL is like a weapons-pack or “Toolkit” of C++.
It contains some very useful data structures and algorithms.
STL is one of the reasons why C++ is best for CP.
To start using:
#include<bits/stdc++.h>
using namespace std;
// Now all STL Containers and Functions are ready for use
WATCH MY YOUTUBE
VIDEO FOR DEEP
EXPLANATION OF
THESE SLIDES
About Me
Hi, I am Utkarsh Gupta.
Upcoming Google Software Engineer. (Offcampus, Google contacted me)
I am one of the best Competitive Programmers in India.
Subscribe to my YT Channel for more content
Achievements:
India Ranks 2, 2, 2, 3 in Google Kickstart Round A,B,C,D respectively.
Grandmaster on Codeforces (India Rank 2)
7 star coder on Codechef
Watch me do Leetcode Weekly Contest in less than half time
Not Bragging, just telling it to learners so that they
learn confidently with faith in the teacher.
Benefits of STL
● Using STL, you can write shorter code that runs faster
● The prewritten codes in STL are extremely error-free and optimized.
● As you study advanced concepts - STL will be very important
○ Vector is used for graph adjacency list
○ pairs and sets are used for dijkstra algorithm in graph
○ And many more...
Vector
It is a dynamic sized array. Number of elements can be increased or decreased.
(In Java same behaviour is shown by ArrayList).
vector<int> v; // empty vector of integers
vector<int> v(10); // vector of integers with 10 elements (all 0)
vector<char> v(10,’h’); // vector of chars with 10 elements (all ‘h’)
Important Functions:
v.push_back(x) - insert the value x to the end of the vector. O(1)
v.pop_back() - erase the last element. O(1)
v.clear() - erase all elements. O(n)
v.size() - returns the current size of the vector. O(1)
[] operator - can be used to access elements like an array. O(1)
cout << v[0]; // prints the first element in the vector
Importance of Vector
There are hundreds of use-cases but some of them might be too advanced to
beginners, so here is an easier example.
Given N numbers in input, print 2 lines, in first line, all even integers in sorted
order, in second line, all odd integers in sorted order.
Solution hint:
Make 2 vectors - one for even elements, other for odd elements, push_back() the
elements into the correct vector accordingly. Then sort both vectors and print.
(Note: This problem can be done without vectors also, but it is easier with vectors)
sort()
This function can be used to sort an array or a vector or a string. The underlying
sorting algorithm is called the gcc_sort which is a hybrid algorithm which is
implemented in a very efficient way. O(NlogN)
If you manually write a sorting algorithm, it’ll be slower than this.
Usage:
int a[n];
sort(a,a+n);
vector<int> v;
sort(v.begin(),v.end());
string s;
sort(s.begin(),s.end());
Note: begin() and end() are called iterators, we’ll discuss them later.
In short, they’re a little bit similar to pointers.
Pair
Pair is a way of creating a Composite-Datatype composed of 2 different
primitive/composite datatypes.
pair<int,int> p; // a pair of 2 ints
pair<int,string> p; // a pair of an int and a string
pair<int,pair<int,string>> p; // a pair of int and (pair of int and string)
pair<vector<int>,string> p; // a pair of a (vector of int) and a string
Access elements using .first and .second
pair<string,int> p = {“hello”,6};
cout << p.first << “ “ << p.second; // prints: hello 6
Advantages:
In case, you want to return multiple values from a function.
(see next slide for the main advantage)
Sorting arrays/vectors of Pairs (Very Useful)
Say we have an array of pairs.
pair<int,int> p[5]; // an array of 5 pairs
p[0] = {1,2}; p[1] = {5,2}; p[2] = {8,1}; p[3] = {1,0}; p[4] = {3,4}
Let’s sort this array:
sort(p,p+5);
Now the array looks like:
[{1,0}, {1,2}, {3,4}, {5,2}, {8,1}]
Sorting is done in a way that the ordering is done by the “first” element, but wherever the “first” is equal,
the ties are broken by comparing second.
Try this question:
Given a list of names and scores of students, print the names of students in decreasing order of scores.
Iterators
These behave a lot like pointers.
vector<int> v = {10, 15, 12, 5, 20};
vector<int>::iterator it = v.begin();
// OR
auto it = v.begin();
cout << *it; // 10
it++;
cout << *it; // 15
it--;
cout << *it; // 10
cout << *(it + 3); // 5
int a[5] = {10, 15, 12, 5, 20};
int *p = a;
cout << *p; // 10
p++;
cout << *p; // 15
p--;
cout << *p; // 10
cout << *(p + 3); // 5
“auto” keyword is used to
deduce datatype
automatically
NOTE: v.end() is the iterator to a non-existent
element (after the last element)
Set
Set is a container which keeps a unique copy of every element in sorted order.
(In Java same behaviour is shown by TreeSet).
set<int> s; // empty set of integers
set<string> s; // empty set of strings
Important Functions:
s.insert(x) - insert the value x into set, do nothing if already present. O(log N)
s.erase(x) - erase the value x from set if present. O(log N)
s.count(x) - returns 0 if x is not in set and 1 if x is in set. O(log N)
s.clear() - erase all elements. O(n)
s.size() - returns the current size of the set. O(1)
WRONG: cout << s[0]; // [] operator doesn’t work with set
Set Iterators
Set iterators offer less features than vector iterators.
auto it = s.begin(); // it is the iterator to the first element
it++, it--, ++it, --it -> These are all valid and work in O(logN) time
Functions related to set iterators:
s.find(x): returns iterator to element with value x. Returns s.end() if not found. O(logN)
s.lower_bound(x): returns iterator to the first element which is >= x. Returns s.end() if not found. O(logN)
s.upper_bound(x): returns iterator to the first element which is > x. Returns s.end() if not found. O(logN)
s.erase(it): erases the element with iterator it. O(logN)
Both of the next 2 lines are exactly same.
if(s.find(10) == s.end()) cout << “Not Found”;
if(s.count(10) == 0) cout << “Not Found”;
NOTE: s.end() is the iterator to a non-existent
element (after the last element)
NOTE: (it + 5) or it += 2 etc are INVALID. To advance multiple steps, do it++ multiple times.
Map
You can think of these as special arrays in which the indices(keys) of elements
can be negative or very big or even strings! These are like python-dictionaries. (In
Java same behaviour is shown by TreeMap).
map<key_datatype, value_datatype> m;
map<string, int> m; // defines a map in which the keys of elements are strings
Now we can use it like:
m[“hello”] = 50;
m[“world”] = 12;
cout << m[“hello”] << “ “ << m[“world”]; // 50 12
map<int,int> m;
m[-234] = 49; // negative ints are also valid as keys
Very common use-case: Count frequency of various objects
NOTE: Maps are very similar to
sets, in sets the values are unique
and sorted, in maps, the keys are
unique and sorted
Map (Continued)
m.clear() - Clears a map
m[key] - value of element with key. O(logN)
m.count(key), m.find(key), m.erase(key),
m.lower_bound(key), m.upper_bound(key) - similar to set
Map Iterators behave similar to set iterators, but upon doing *it you instead of
getting the value, you get a pair of {key, value}
Examples:
map<string, double> m;
// insert values in map
auto it = m.find(“utkarsh”);
pair<string, double> p = *it; // {“utkarsh”, m[“utkarsh] }
BONUS:
(*it).first and (*it).second
Can instead be written as
it -> first
it -> second
Iterating Containers
for(auto it = s.begin(); it != s.end(); it++){
// *it
}
This works for all three: set, map and vector
Shorthand:
set<int> s;
for(int x:s){
// x
}
vector<int> v;
for(int x:v){
// x
}
map<int,int> m;
for(pair<int,int> x:v){
// x.first, x.second
}
Try Out These Problems
https://codeforces.com/problemset/problem/22/A (SET)
https://codeforces.com/problemset/problem/782/A (SET)
https://codeforces.com/problemset/problem/4/C (MAP)
https://codeforces.com/contest/903/problem/C (MAP - medium level)
Do these also without knowing which containers to use:
https://www.spoj.com/problems/MINSTOCK/
https://codeforces.com/problemset/problem/799/B
Also, keep practicing problems from Codeforces, div2 B and C often require you to use some STL
containers and functions.
References (Can be used like “Glossary”)
Any STL container or function, you want to learn about: Just google search
“Cplusplus [container name]”
For example: “Cplusplus vector” gives the following result:
https://www.cplusplus.com/reference/vector/vector/
Similarly:
https://www.cplusplus.com/reference/set/set/
https://www.cplusplus.com/reference/map/map/
BEST OF LUCK!
Next Slides are not for
Beginners, they have some
intermediate level stuff,
continue only if you have
good grasp of STL and C++
Custom Comparators (Less Commonly Needed)
You can define your own rule for sorting!
For example:
bool decreasing_order(int x, int y){
return x > y;
}
int a[10];
sort(a, a+10, decreasing_order); // sorts in descending order
The comparator with arguments (x,y) should return true IF AND ONLY IF, x is
necessarily on the left of y in the sorted array. Read more here.
Exercise: Define Custom Comparator to sort pairs in increasing order of first and if
there are ties, break those in decreasing order of second.
NOTE: Using Comparator
Classes, we can apply
custom sorting rules to
sets and maps also
Further Study (Not Relevant for Beginners)
Read about these containers on your own, it should be easy because most of the
important concepts are already covered. These are less commonly used so you
don’t need to worry about these for a long time.
● queue
● stack
● deque
● priority_queue
● multiset / multimap -> can store duplicates (too complex for beginners)
● unordered_set / unordered_map (like HashSet or HashMap in Java)
NOTE: unordered set and map are not-reliable and can perform bad in certain
situations, beginners should always avoid them.

More Related Content

Similar to C++ STL (quickest way to learn, even for absolute beginners).pptx

Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxCatherineVania1
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updatedvrgokila
 
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxAssg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxfestockton
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Guy Lebanon
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202Mahmoud Samir Fayed
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingMandeep Singh
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and LibrariesVenugopalavarma Raja
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptadityavarte
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptOliverKane3
 

Similar to C++ STL (quickest way to learn, even for absolute beginners).pptx (20)

Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxAssg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202
 
Bt0065
Bt0065Bt0065
Bt0065
 
B T0065
B T0065B T0065
B T0065
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Data structures
Data structuresData structures
Data structures
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Matlab Manual
Matlab ManualMatlab Manual
Matlab Manual
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 

More from Abhishek Tirkey

Intermediate Code Generation.pptx
Intermediate Code Generation.pptxIntermediate Code Generation.pptx
Intermediate Code Generation.pptxAbhishek Tirkey
 
Unit 1_Oral Communication and Group Activities (1).pptx
Unit 1_Oral Communication and Group Activities (1).pptxUnit 1_Oral Communication and Group Activities (1).pptx
Unit 1_Oral Communication and Group Activities (1).pptxAbhishek Tirkey
 
patternrecognisation.pdf
patternrecognisation.pdfpatternrecognisation.pdf
patternrecognisation.pdfAbhishek Tirkey
 
ALGAE Advance Microbiology.pptx
ALGAE Advance Microbiology.pptxALGAE Advance Microbiology.pptx
ALGAE Advance Microbiology.pptxAbhishek Tirkey
 
CLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptx
CLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptxCLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptx
CLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptxAbhishek Tirkey
 
PROPOGATING PLANTS BY AIR LAYERING.pptx
PROPOGATING PLANTS BY AIR LAYERING.pptxPROPOGATING PLANTS BY AIR LAYERING.pptx
PROPOGATING PLANTS BY AIR LAYERING.pptxAbhishek Tirkey
 
CLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptx
CLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptxCLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptx
CLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptxAbhishek Tirkey
 
Cytological proof of crossing over
Cytological proof of crossing overCytological proof of crossing over
Cytological proof of crossing overAbhishek Tirkey
 

More from Abhishek Tirkey (9)

Intermediate Code Generation.pptx
Intermediate Code Generation.pptxIntermediate Code Generation.pptx
Intermediate Code Generation.pptx
 
Unit 1_Oral Communication and Group Activities (1).pptx
Unit 1_Oral Communication and Group Activities (1).pptxUnit 1_Oral Communication and Group Activities (1).pptx
Unit 1_Oral Communication and Group Activities (1).pptx
 
UNIT 2 (1).pptx
UNIT 2 (1).pptxUNIT 2 (1).pptx
UNIT 2 (1).pptx
 
patternrecognisation.pdf
patternrecognisation.pdfpatternrecognisation.pdf
patternrecognisation.pdf
 
ALGAE Advance Microbiology.pptx
ALGAE Advance Microbiology.pptxALGAE Advance Microbiology.pptx
ALGAE Advance Microbiology.pptx
 
CLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptx
CLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptxCLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptx
CLASSIFCATION OF HORTICULTURE PLANT BASED ON STEM AND LEAF TEXTURE.pptx
 
PROPOGATING PLANTS BY AIR LAYERING.pptx
PROPOGATING PLANTS BY AIR LAYERING.pptxPROPOGATING PLANTS BY AIR LAYERING.pptx
PROPOGATING PLANTS BY AIR LAYERING.pptx
 
CLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptx
CLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptxCLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptx
CLASSIFICATION OF HORTICULTURE PLANT BY SEASON.pptx
 
Cytological proof of crossing over
Cytological proof of crossing overCytological proof of crossing over
Cytological proof of crossing over
 

Recently uploaded

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 

Recently uploaded (20)

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 

C++ STL (quickest way to learn, even for absolute beginners).pptx

  • 1. C++ STL (quickest way to learn, even for absolute beginners) C++ STL is like a weapons-pack or “Toolkit” of C++. It contains some very useful data structures and algorithms. STL is one of the reasons why C++ is best for CP. To start using: #include<bits/stdc++.h> using namespace std; // Now all STL Containers and Functions are ready for use WATCH MY YOUTUBE VIDEO FOR DEEP EXPLANATION OF THESE SLIDES
  • 2. About Me Hi, I am Utkarsh Gupta. Upcoming Google Software Engineer. (Offcampus, Google contacted me) I am one of the best Competitive Programmers in India. Subscribe to my YT Channel for more content Achievements: India Ranks 2, 2, 2, 3 in Google Kickstart Round A,B,C,D respectively. Grandmaster on Codeforces (India Rank 2) 7 star coder on Codechef Watch me do Leetcode Weekly Contest in less than half time Not Bragging, just telling it to learners so that they learn confidently with faith in the teacher.
  • 3. Benefits of STL ● Using STL, you can write shorter code that runs faster ● The prewritten codes in STL are extremely error-free and optimized. ● As you study advanced concepts - STL will be very important ○ Vector is used for graph adjacency list ○ pairs and sets are used for dijkstra algorithm in graph ○ And many more...
  • 4. Vector It is a dynamic sized array. Number of elements can be increased or decreased. (In Java same behaviour is shown by ArrayList). vector<int> v; // empty vector of integers vector<int> v(10); // vector of integers with 10 elements (all 0) vector<char> v(10,’h’); // vector of chars with 10 elements (all ‘h’) Important Functions: v.push_back(x) - insert the value x to the end of the vector. O(1) v.pop_back() - erase the last element. O(1) v.clear() - erase all elements. O(n) v.size() - returns the current size of the vector. O(1) [] operator - can be used to access elements like an array. O(1) cout << v[0]; // prints the first element in the vector
  • 5. Importance of Vector There are hundreds of use-cases but some of them might be too advanced to beginners, so here is an easier example. Given N numbers in input, print 2 lines, in first line, all even integers in sorted order, in second line, all odd integers in sorted order. Solution hint: Make 2 vectors - one for even elements, other for odd elements, push_back() the elements into the correct vector accordingly. Then sort both vectors and print. (Note: This problem can be done without vectors also, but it is easier with vectors)
  • 6. sort() This function can be used to sort an array or a vector or a string. The underlying sorting algorithm is called the gcc_sort which is a hybrid algorithm which is implemented in a very efficient way. O(NlogN) If you manually write a sorting algorithm, it’ll be slower than this. Usage: int a[n]; sort(a,a+n); vector<int> v; sort(v.begin(),v.end()); string s; sort(s.begin(),s.end()); Note: begin() and end() are called iterators, we’ll discuss them later. In short, they’re a little bit similar to pointers.
  • 7. Pair Pair is a way of creating a Composite-Datatype composed of 2 different primitive/composite datatypes. pair<int,int> p; // a pair of 2 ints pair<int,string> p; // a pair of an int and a string pair<int,pair<int,string>> p; // a pair of int and (pair of int and string) pair<vector<int>,string> p; // a pair of a (vector of int) and a string Access elements using .first and .second pair<string,int> p = {“hello”,6}; cout << p.first << “ “ << p.second; // prints: hello 6 Advantages: In case, you want to return multiple values from a function. (see next slide for the main advantage)
  • 8. Sorting arrays/vectors of Pairs (Very Useful) Say we have an array of pairs. pair<int,int> p[5]; // an array of 5 pairs p[0] = {1,2}; p[1] = {5,2}; p[2] = {8,1}; p[3] = {1,0}; p[4] = {3,4} Let’s sort this array: sort(p,p+5); Now the array looks like: [{1,0}, {1,2}, {3,4}, {5,2}, {8,1}] Sorting is done in a way that the ordering is done by the “first” element, but wherever the “first” is equal, the ties are broken by comparing second. Try this question: Given a list of names and scores of students, print the names of students in decreasing order of scores.
  • 9. Iterators These behave a lot like pointers. vector<int> v = {10, 15, 12, 5, 20}; vector<int>::iterator it = v.begin(); // OR auto it = v.begin(); cout << *it; // 10 it++; cout << *it; // 15 it--; cout << *it; // 10 cout << *(it + 3); // 5 int a[5] = {10, 15, 12, 5, 20}; int *p = a; cout << *p; // 10 p++; cout << *p; // 15 p--; cout << *p; // 10 cout << *(p + 3); // 5 “auto” keyword is used to deduce datatype automatically NOTE: v.end() is the iterator to a non-existent element (after the last element)
  • 10. Set Set is a container which keeps a unique copy of every element in sorted order. (In Java same behaviour is shown by TreeSet). set<int> s; // empty set of integers set<string> s; // empty set of strings Important Functions: s.insert(x) - insert the value x into set, do nothing if already present. O(log N) s.erase(x) - erase the value x from set if present. O(log N) s.count(x) - returns 0 if x is not in set and 1 if x is in set. O(log N) s.clear() - erase all elements. O(n) s.size() - returns the current size of the set. O(1) WRONG: cout << s[0]; // [] operator doesn’t work with set
  • 11. Set Iterators Set iterators offer less features than vector iterators. auto it = s.begin(); // it is the iterator to the first element it++, it--, ++it, --it -> These are all valid and work in O(logN) time Functions related to set iterators: s.find(x): returns iterator to element with value x. Returns s.end() if not found. O(logN) s.lower_bound(x): returns iterator to the first element which is >= x. Returns s.end() if not found. O(logN) s.upper_bound(x): returns iterator to the first element which is > x. Returns s.end() if not found. O(logN) s.erase(it): erases the element with iterator it. O(logN) Both of the next 2 lines are exactly same. if(s.find(10) == s.end()) cout << “Not Found”; if(s.count(10) == 0) cout << “Not Found”; NOTE: s.end() is the iterator to a non-existent element (after the last element) NOTE: (it + 5) or it += 2 etc are INVALID. To advance multiple steps, do it++ multiple times.
  • 12. Map You can think of these as special arrays in which the indices(keys) of elements can be negative or very big or even strings! These are like python-dictionaries. (In Java same behaviour is shown by TreeMap). map<key_datatype, value_datatype> m; map<string, int> m; // defines a map in which the keys of elements are strings Now we can use it like: m[“hello”] = 50; m[“world”] = 12; cout << m[“hello”] << “ “ << m[“world”]; // 50 12 map<int,int> m; m[-234] = 49; // negative ints are also valid as keys Very common use-case: Count frequency of various objects NOTE: Maps are very similar to sets, in sets the values are unique and sorted, in maps, the keys are unique and sorted
  • 13. Map (Continued) m.clear() - Clears a map m[key] - value of element with key. O(logN) m.count(key), m.find(key), m.erase(key), m.lower_bound(key), m.upper_bound(key) - similar to set Map Iterators behave similar to set iterators, but upon doing *it you instead of getting the value, you get a pair of {key, value} Examples: map<string, double> m; // insert values in map auto it = m.find(“utkarsh”); pair<string, double> p = *it; // {“utkarsh”, m[“utkarsh] } BONUS: (*it).first and (*it).second Can instead be written as it -> first it -> second
  • 14. Iterating Containers for(auto it = s.begin(); it != s.end(); it++){ // *it } This works for all three: set, map and vector Shorthand: set<int> s; for(int x:s){ // x } vector<int> v; for(int x:v){ // x } map<int,int> m; for(pair<int,int> x:v){ // x.first, x.second }
  • 15. Try Out These Problems https://codeforces.com/problemset/problem/22/A (SET) https://codeforces.com/problemset/problem/782/A (SET) https://codeforces.com/problemset/problem/4/C (MAP) https://codeforces.com/contest/903/problem/C (MAP - medium level) Do these also without knowing which containers to use: https://www.spoj.com/problems/MINSTOCK/ https://codeforces.com/problemset/problem/799/B Also, keep practicing problems from Codeforces, div2 B and C often require you to use some STL containers and functions.
  • 16. References (Can be used like “Glossary”) Any STL container or function, you want to learn about: Just google search “Cplusplus [container name]” For example: “Cplusplus vector” gives the following result: https://www.cplusplus.com/reference/vector/vector/ Similarly: https://www.cplusplus.com/reference/set/set/ https://www.cplusplus.com/reference/map/map/ BEST OF LUCK!
  • 17. Next Slides are not for Beginners, they have some intermediate level stuff, continue only if you have good grasp of STL and C++
  • 18. Custom Comparators (Less Commonly Needed) You can define your own rule for sorting! For example: bool decreasing_order(int x, int y){ return x > y; } int a[10]; sort(a, a+10, decreasing_order); // sorts in descending order The comparator with arguments (x,y) should return true IF AND ONLY IF, x is necessarily on the left of y in the sorted array. Read more here. Exercise: Define Custom Comparator to sort pairs in increasing order of first and if there are ties, break those in decreasing order of second. NOTE: Using Comparator Classes, we can apply custom sorting rules to sets and maps also
  • 19. Further Study (Not Relevant for Beginners) Read about these containers on your own, it should be easy because most of the important concepts are already covered. These are less commonly used so you don’t need to worry about these for a long time. ● queue ● stack ● deque ● priority_queue ● multiset / multimap -> can store duplicates (too complex for beginners) ● unordered_set / unordered_map (like HashSet or HashMap in Java) NOTE: unordered set and map are not-reliable and can perform bad in certain situations, beginners should always avoid them.