113. C++ STL Tips.
Table of Contents
Some STL Tips and Time Complexities:
Data Structures
-
Vector
- Initialize a vector of size n, with int k:
vector<int> v(n, k)
- Initialize a matrix of m rows and n columns and initialise it with int k:
vector<vector<int>> a(m, vector<int>(n, k));
- Ops that take O(1): begin(), end(), size(), at(), push_back(), pop_back().
- Ops that take O(n): insert(), erase(), clear().
list
is similar to vector, but the underlying data structure becomes a DLL. Now you also get push_front() and pop_front() ops in O(1).
- Initialize a vector of size n, with int k:
-
Stack
- Ops: push(), pop(), top(), empty() all are O(1)
-
Queue
- Ops: push(), pop(), front(), back(), empty() all are O(1)
- Deque is also some but now it gives you push_back(), pop_back(), push_front(), pop_front() options.
-
Set
- In an unordered set all ops are O(1): insert(), erase(), find(), empty()
- In a set, insert(), erase() and find() are all O(logn). Clear is O(n).
- Creating a set using vector:
set<int> s(v.begin(), v.end());
-
Map
- Unordered map, all ops are O(1) on average: insert(), find(), erase(). But these can go to O(N) worst case.
- Ordered map: all ops are O(logN)
-
Priority Queue
priority_queue<int> pq
is a maxHeap by default.- To make a mean heap:
priority_queue<X, vector<X>, greater<X>> pq
. - Ops: push() and pop() are O(logN).
- top() is O(1)
Note: operations such as begin(), end(), empty(), size(), front() are always O(1) for almost all DS.
Algorithms
- Sorting
sort(v.begin(), v.end())
takes O(NlogN) on average.- Using custom comparators generally don't affect the time complexity. If you want to sort in descending order: Return true if first element is greater than the second: E.g.:
static bool sortcol(int a, int b) return a > b; //for 1D vector, descending order static bool sortcol(vector<int> a, vector<int> b) return a[0] < b[0]; //for 2D vector such that arranged by ascending order by the first element.