SlideShare una empresa de Scribd logo
1 de 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.

Más contenido relacionado

La actualidad más candente (20)

Programación 3: colas
Programación 3: colasProgramación 3: colas
Programación 3: colas
 
Data structure
Data structureData structure
Data structure
 
Bfs new
Bfs newBfs new
Bfs new
 
Arrays
ArraysArrays
Arrays
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
 
Stack
StackStack
Stack
 
Listas Enlazadas
Listas EnlazadasListas Enlazadas
Listas Enlazadas
 
Sets
SetsSets
Sets
 
Trees and graphs
Trees and graphsTrees and graphs
Trees and graphs
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Array in-c
Array in-cArray in-c
Array in-c
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
INTRODUCTION TO ALGORITHMS Third Edition
INTRODUCTION TO ALGORITHMS Third EditionINTRODUCTION TO ALGORITHMS Third Edition
INTRODUCTION TO ALGORITHMS Third Edition
 
Listas en C#
Listas en C#Listas en C#
Listas en C#
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
Connectivity of graphs
Connectivity of graphsConnectivity of graphs
Connectivity of graphs
 
R Programming: Variables & Data Types
R Programming: Variables & Data TypesR Programming: Variables & Data Types
R Programming: Variables & Data Types
 
Arrays bidimensionales
Arrays bidimensionalesArrays bidimensionales
Arrays bidimensionales
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 

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

Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template LibraryAnirudh Raja
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUadAccount
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
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
 

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

Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template Library
 
Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
Op ps
Op psOp ps
Op ps
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
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
 

Último

Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls AgencyHire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls AgencySheetal Arora
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSarthak Sekhar Mondal
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPirithiRaju
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksSérgio Sacani
 
Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfrohankumarsinghrore1
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PPRINCE C P
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)PraveenaKalaiselvan1
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)Areesha Ahmad
 
fundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomologyfundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomologyDrAnita Sharma
 
Pulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceuticsPulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceuticssakshisoni2385
 
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bSérgio Sacani
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxAArockiyaNisha
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Lokesh Kothari
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )aarthirajkumar25
 
Botany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfBotany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfSumit Kumar yadav
 
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 60009654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000Sapana Sha
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxgindu3009
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfSumit Kumar yadav
 

Último (20)

Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls AgencyHire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdf
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disks
 
Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdf
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C P
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)
 
fundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomologyfundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomology
 
Pulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceuticsPulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceutics
 
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )
 
Botany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfBotany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdf
 
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 60009654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptx
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdf
 

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.