C++ Data Structures Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/18253/
Pointers Maps
Storing, data type of pointers and variables must be the same map<string, int> M;
&var Returns address of memory location of variable M[“hello”] = 2;
M[“asd”] = 986;
data_type Initialize. Put * in front of name
*pointer; M.count(“asd”); // returns 1
M.count(“doesnt_exist”); // returns 0
*pointer Returns value at the memory location stored by
M.size();
pointer
// Check for the existence of some key in the map -
Array variables are actually pointers to the first element in the array.
O(log N)
The amount that your pointer moves from an arithmetic operation
it = M.find(“asd”); //returns the iterator to
*array Returns first element in array
“asd”
*(array+2) Returns third element in array it = M.upper_bound("aaa");
◎ Variables that you declare are stored in a memory location in your it = M.lower_bound("aaa");
computer if (it == M.end())
◎ The address of these memory locations can be stored in pointers cout << "Does not exist\n";
◎ Addresses are in hexadecimal //Iteration
for (auto it = mp.begin(); it != mp.end(); ++it)
Iterators {
//Append ::iterator to your data type declaration cout << it.first << “, “ << it.second <<
to create an iterator of “\n”;
that data type }
vector<int>::iterator it; // declares an A data structure that takes in any data[key]
iterator of vector<int> Gives you the associated value stored through O(log N) magic
// loops from the start to end of vi
for(vector<int>::iterator it = vi.begin(); it Best used when you need to lookup certain values in O(log N) time
!= vi.end(); it++) that are associated with other values
cout << *it << " "; // outputs 1 2 3 4
deque<int> d; Queue
deque<int>::iterator it; queue<int> q;
it = d.begin(); //Points to first element q.push(5); // Inserts/ Enqueue element at the back
it++; // Points to next element of the queue
it = d.end(); // Points to Last element q.front(); // Returns element atb the front of the
it--; // Points to previous element queue
cout << *it; // outputs the element it is pointing q.pop // Removes (Dequeues) element from the front
Iterators are essentially pointers to an STL data structure of the queue
q.empty(); // Returns boolean value of whether
queue is empty
First In First Out data structure where elements can only be added to
the back and accessed at the front
By Hackin7 Published 12th December, 2018. Sponsored by CrosswordCheats.com
cheatography.com/hackin7/ Last updated 27th December, 2019. Learn to solve cryptic crosswords!
Page 1 of 5. http://crosswordcheats.com
C++ Data Structures Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/18253/
Priority Queue Fenwick tree (cont)
priority_queue<data_type> pq; // Largest at top > void fenwick_range_update(int pos_a, int pos_b, int val){
priority_queue<data_type, vector<data_typ‐ //TLE way
e>, greater<data_type> > //for (int i=pos_a;i<=pos_b;i++){fenwick_update(i, val);}
pq; // Smallest at top fenwick_update(pos_a, val);
pq.push(5); // pushes element into it. Duplicates fenwick_update(pos_b+1, -val);
are allowed }
////PURQ////////////// ////////////////////////////////////////
pq.top() // Returns largest or smallest element
long long fenwick_range_query(int pos_a, int pos_b) {
pq.pop() // Removes largest or smallest element
return fenwick_query(pos_b) - fenwick_query(pos_a-1);
pq.size(); // Returns size
}
pq.empty(); Check if queue is empty
////RURQ//////////////////////////////////////////////////////
Like a queue except that only the element with the greatest priority long long B1[100001];long long B2[100001];
(eg. largest/smallest) can be accessed void base_update(long long *ft, int pos, long long value){
//Add largest power of 2 dividing x / Last set bit in number x
Fenwick tree for (; pos <= N; pos += pos&(-pos))
//Below here can mix & match ft[pos] += value;
long long ft[100001]; // note: this fenwick tree }
void rurq_range_update(int a, int b,long long v){
is 1-indexed.
base_update(B1, a, v);
////PU‐
base_update(B1, b + 1, -v);
PQ////////////////////////////////////
base_update(B2, a, v * (a-1));
//////////////////
base_update(B2, b + 1, -v * b);
void fenwick_update(int pos, long long value) {
}
while (pos <= N) {
void rurq_point_update(int a, long long v){
//cout<<"Fenwick Updating: "‐
rurq_range_update(a,a,v);
<<pos<<","<<value<<endl; }
ft[pos] += value; long long base_query(long long *ft,int b){
long long sum = 0;
pos += pos&-pos; for(; b > 0; b -= b&(-b))
} sum += ft[b];
}
long long fenwick_query(int pos) {
long long sum = 0;
while (pos) { // while p > 0
sum += ft[pos];
pos -= pos&-pos;
}
return sum;
}
////RU‐
PQ////////////////////////////////////
//////////////////
By Hackin7 Published 12th December, 2018. Sponsored by CrosswordCheats.com
cheatography.com/hackin7/ Last updated 27th December, 2019. Learn to solve cryptic crosswords!
Page 2 of 5. http://crosswordcheats.com
C++ Data Structures Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/18253/
Fenwick tree (cont) Stack
> return sum; stack<int> s;
} s.push(5); // push an element onto the stack -
// Return sum A[1...b] O(1)
long long rurq_query(int b){ s.pop(); // pop an element from the stack - O(1)
return base_query(B1, b) * b - base_query(B2, b); s.top(); // access the element at the top of the
} stack - O(1)
//Return sum A[a...b]
s.empty(); // whether stack is empty - O(1)
long long rurq_range_query(int a,int b){
return rurq_query(b) - rurq_query(a-1); First-In-Last-Out data structure
} Only Element at the top can be accessed / removed
Pair Vector
// Initialise // Initialize
pair<data_type_1, data_type_2> variable; vector<data_type> v;
// OR v.push_back(value); // Add element to back
pair<data_type_1, data_type_2> variable = v.pop_back() // Remove last element
make_pair(value1,value2); v.clear(); // Remove all elements
// Store values v[index] // Return element of index
variable.first = value; v.back(); // Return last element
variable second = value; v.size(); // Return Size of vector
// Retrieve values v.empty() // Return boolean value of whether
cout <<variable first << " " << variable.second vector is empty
<< endl; Like arrays but re-sizable. You can add and remove any number of
//Nesting pairs elements from any position.
pair<int, pair<int, int> > a;
a.first = 5; Sets and Multisets
a.second.first = 6; set<int> s; set<int>::iterator it;
a.second.second = 7; multiset<int> s; multiset<int>::iterator it;
Stores a pair of values s.insert(10);
it = s.find(8)
it = s.upper_bound(7);
it = s.lower_bound(7);
s.erase(10); //Remove element from set
s.erase(it) //Can also use iterators
s.empty();
By Hackin7 Published 12th December, 2018. Sponsored by CrosswordCheats.com
cheatography.com/hackin7/ Last updated 27th December, 2019. Learn to solve cryptic crosswords!
Page 3 of 5. http://crosswordcheats.com
C++ Data Structures Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/18253/
Sets and Multisets (cont) Segment Tree (cont)
> s.clear(); > //Min value stored
// to loop through a set val = 0; lazyadd = 0;
for(it = s.begin(); it != s.end(); it++) if (start!=end) {
cout << *it << " "; // outputs 2 7 10 left = new node(start,mid);
right = new node(mid+1,end);
In a set: All elements are sorted and no duplicates
}
Multisets can store duplicates though
}
Deque
int value(){
deque<int> d;
if (start==end){
// access an element / modify an element (0-indexed val += lazyadd;lazyadd = 0;return val;
as well) - O(1) }else{
d[0] = 2; // change deque from {5, 10} to {2, 10} val += lazyadd;
d[0]; // returns a value of 2 // Propagate Lazyadd
d.back(); // get back (last) element - O(1) right->lazyadd += lazyadd;
d.front(); // get front (first) element - O(1) left->lazyadd += lazyadd;
d.clear() // Remove all elements lazyadd = 0;
d.push_back(5); // add an element to the back - return val;
O(1) }
d.push_front(10); // add an element to the front }
- O(1)
void addRange(int lower_bound, int upper_bound, int val_to_add){
d.pop_back(); // remove the back (last) element -
if (start == lower_bound && end == upper_bound){
O(1)
lazyadd += val_to_add;
d.pop_front(); // remove the front (first)
}else{
element - O(1)
if (lower_bound > mid){
d.size(); //Return size
right->addRange(lower_bound, upper_bound, val_to_add);
d.empty // Whether queue is empty
}else if (upper_bound <= mid){
A stack and queue combined. left->addRange(lower_bound, upper_bound, val_to_add);
...or a vector that and be pushed and popped from the front as well. }else{
left->addRange(lower_bound, mid, val_to_add);
Deque = Double Ended Queue! right->addRange(mid+1, upper_bound, val_to_add);
Segment Tree
struct node {
int start, end, mid, val, lazyadd;
node
left, right;
node(int _s, int _e) {
//Range of values stored
start = _s; end = _e; mid =
(start+end)/2;
By Hackin7 Published 12th December, 2018. Sponsored by CrosswordCheats.com
cheatography.com/hackin7/ Last updated 27th December, 2019. Learn to solve cryptic crosswords!
Page 4 of 5. http://crosswordcheats.com
C++ Data Structures Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/18253/
Segment Tree (cont) Segment Tree (cont)
> } > }
val = min(left->value(), right->value()); //End//////////////////////////////////////////
} }
}
} *root;
// Update position to new_value // O(log N) void init(int N){
void update(int pos, int new_val) { //position x to new value root = new node(0, N-1); // creates seg tree of size n
if (start==end) { val=new_val; return; } }
if (pos>mid) right->update(pos, new_val); void update(int P, int V){
if (pos<=mid) left->update(pos, new_val); root->update(P,V);
val = min(left->val, right->val); }
} int query(int A, int B){
int val = root->rangeMinimumQuery(A,B);
// Range Minimum Query // O(log N) return val;
int rangeMinimumQuery(int lower_bound, int upper_bound) { }
//cout<<"Node:"<<start<<" "<<end<<" "<<mid<<" "<<val<<endl;
//If Query Range Corresponds////////////////
if (start==lower_bound && end==upper_bound){
return value();
}
//Query Right Tree if range only lies there
else if (lower_bound > mid){
return right->rangeMinimumQuery(lower_bound, upper_‐
bound);
}
//Query Left Tree if range only lies there
else if (upper_bound <= mid){
return left->rangeMinimumQuery(lower_bound, upper_‐
bound);
}
//Query both ranges as range spans both trees
else{
return min(left->rangeMinimumQuery(lower_bound, mid),r‐
ight->rangeMinimumQuery(mid+1, upper_bound));
By Hackin7 Published 12th December, 2018. Sponsored by CrosswordCheats.com
cheatography.com/hackin7/ Last updated 27th December, 2019. Learn to solve cryptic crosswords!
Page 5 of 5. http://crosswordcheats.com