C++ STL (quickest way to learn, even for absolute beginners)
C++ STL (quickest way to learn, even for absolute beginners)
To start using:
#include<bits/stdc++.h>
using namespace std;
// Now all STL Containers and Functions are ready for use
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)
Usage:
Note: begin() and end() are called iterators, we’ll discuss them later.
In short, they’re a little bit similar to pointers.
Advantages:
In case, you want to return multiple values from a function.
Pair (see next slide for the main advantage)
NOTE: (it + 5) or it += 2 etc are INVALID. To advance multiple steps, do it++ multiple times.
map<int,int> m;
m[-234] = 49; // negative ints are also valid as keys
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}
BONUS:
(*it).first and (*it).second
Examples: Can instead be written as
map<string, double> m; it -> first
it -> second
// insert values in map
auto it = m.find(“utkarsh”);
pair<string, double> p = *it; // {“utkarsh”, m[“utkarsh] }
Iterating Containers
for(auto it = s.begin(); it != s.end(); it++){
// *it
}
This works for all three: set, map and vector
Shorthand:
vector<int> v; set<int> s; map<int,int> m;
// x // x // x.first, x.second
} } }
Try Out These Problems
https://codeforces.com/problemsext/problem/22/A (SET)
https://codeforces.com/problemset/problem/782/A (SET)
https://codeforces.com/problemset/problem/4/C (MAP)
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]”
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: NOTE: Using Comparator
Classes, we can apply
bool decreasing_order(int x, int y){ custom sorting rules to
return x > y; sets and maps also
}
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.
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.