Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C++ Data Structure Cheat Sheet, Cheat Sheet of Data Structures and Algorithms

C++ Data Structure Cheat Sheet

Typology: Cheat Sheet

2021/2022
On special offer
30 Points
Discount

Limited-time offer


Uploaded on 03/05/2022

chi-zhang
chi-zhang ๐Ÿ‡บ๐Ÿ‡ธ

5

(1)

1 document

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C++ Data Structures Cheat Sheet
by Hackin7 via cheatography.com/71996/cs/18253/
Pointers
Storing, data type of pointers and variables must be the same
&var Returns address of memory location of variable
data_type
*pointer;
Initia๎˜lize. Put * in front of name
*pointer Returns value at the memory location stored by
pointer
Array variables are actually pointers to the first el ement in the array.
The amount that your pointer moves from an a rithmetic operation
*array Returns first element in array
*(array+2) Returns third element in array
โ—Ž Variables that you declare are stored in a mem ory location in your
computer
โ—Ž The address of these memory locations can be stored in pointers
โ—Ž Addresses are in hexade๎˜cimal
Iterators
//Append ::iterator to your data type declaration
to create an iterator of
that data type
vector๎˜<in๎˜t>:๎˜:it๎˜erator it; // declares an iterator
of vector๎˜<in๎˜t>
// loops from the start to end of vi
for(ve๎˜cto๎˜r<i๎˜nt>๎˜::i๎˜terator it = vi.beg๎˜in(); it !=
vi.end(); it++)
๎˜ ๎˜ ๎˜ cout << *it << " "; // outputs 1 2 3 4
deque<๎˜int> d;
deque<๎˜int๎˜>::๎˜ite๎˜rator it;
it = d.begin(); //Points to first element
it++; // Points to next element
it = d.end(); // Points to Last element
it--; // Points to previous element
cout << *it; // outputs the element it is pointing
Iterators are essent๎˜ially pointers to an STL data s tructure
Maps
map<string, int> M;
M[โ€œhelloโ€] = 2;
M[โ€œasdโ€] = 986;
M.coun๎˜t(โ€œ๎˜asdโ€); // returns 1
M.coun๎˜t(โ€œ๎˜doe๎˜snt๎˜_ex๎˜istโ€); // returns 0
M.size();
// Check for the existence of some key in the map -
O(log N)
it = M.find๎˜(โ€œa๎˜sdโ€); //returns the iterator to
โ€œasdโ€
it = M.uppe๎˜r_b๎˜oun๎˜d("a๎˜aa");
it = M.lowe๎˜r_b๎˜oun๎˜d("a๎˜aa");
if (it == M.end())
๎˜ ๎˜ ๎˜ cout << "Does not exist๎˜\n";
//Iter๎˜ation
for (auto it = mp.beg๎˜in(); it != mp.end(); ++it) {
๎˜ ๎˜ ๎˜ cout << it.first << โ€œ, โ€œ << it.second << โ€œ\nโ€;
}
A data structure that takes in any data[key]
Gives you the associated value stored through O (log N) magic
Best used when you need to lookup certain valu es in O(log N) time
that are associated with other values
Queue
queue<int> q;
q.push(5); // Inserts/ Enqueue element at the back
of the queue
q.front(); // Returns element atb the front of the
queue
q.pop // Removes (Dequeues) element from the front
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
cheatography.com/hackin7/
Published 12th December, 2018.
Last updated 27th December, 2019.
Page 1 of 5.
Sponsored by CrosswordCheats.com
Learn to solve cryptic crosswords!
http://crosswordcheats.com
pf3
pf4
pf5
Discount

On special offer

Partial preview of the text

Download C++ Data Structure Cheat Sheet and more Cheat Sheet Data Structures and Algorithms in PDF only on Docsity!

by Hackin7 via cheatography.com/71996/cs/18253/

Pointers Storing, data type of pointers and variables must be the same &var Returns address of memory location of variable data_type *pointer; Initialize. Put * in front of name *pointer Returns value at the memory location stored by pointer Array variables are actually pointers to the first element in the array. The amount that your pointer moves from an arithmetic operation *array Returns first element in array *(array+2) Returns third element in array โ—Ž Variables that you declare are stored in a memory location in your computer โ—Ž The address of these memory locations can be stored in pointers โ—Ž Addresses are in hexadecimal Iterators //Append ::iterator to your data type declaration to create an iterator of that data type vector::iterator it; // declares an iterator of vector // loops from the start to end of vi for(vector::iterator it = vi.begin(); it != vi.end(); it++) cout << *it << " "; // outputs 1 2 3 4 deque d; deque::iterator it; it = d.begin(); //Points to first element it++; // Points to next element it = d.end(); // Points to Last element it--; // Points to previous element cout << *it; // outputs the element it is pointing Iterators are essentially pointers to an STL data structure Maps map<string, int> M; M[โ€œhelloโ€] = 2; M[โ€œasdโ€] = 986; M.count(โ€œasdโ€); // returns 1 M.count(โ€œdoesnt_existโ€); // returns 0 M.size(); // Check for the existence of some key in the map - O(log N) it = M.find(โ€œasdโ€); //returns the iterator to โ€œasdโ€ it = M.upper_bound("aaa"); it = M.lower_bound("aaa"); if (it == M.end()) cout << "Does not exist\n"; //Iteration for (auto it = mp.begin(); it != mp.end(); ++it) { cout << it.first << โ€œ, โ€œ << it.second << โ€œ\nโ€; } A data structure that takes in any data[key] Gives you the associated value stored through O(log N) magic Best used when you need to lookup certain values in O(log N) time that are associated with other values Queue queue q; q.push(5); // Inserts/ Enqueue element at the back of the queue q.front(); // Returns element atb the front of the queue q.pop // Removes (Dequeues) element from the front 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 Hackin cheatography.com/hackin7/ Published 12th December, 2018. Last updated 27th December, 2019. Sponsored by CrosswordCheats.com Learn to solve cryptic crosswords!

by Hackin7 via cheatography.com/71996/cs/18253/

Priority Queue priority_queue<data_type> pq; // Largest at top priority_queue<data_type, vector<data_type>, greater<data_type> > pq; // Smallest at top pq.push(5); // pushes element into it. Duplicates are allowed pq.top() // Returns largest or smallest element pq.pop() // Removes largest or smallest element pq.size(); // Returns size pq.empty(); Check if queue is empty Like a queue except that only the element with the greatest priority (eg. largest/smallest) can be accessed Fenwick tree //Below here can mix & match long long ft[100001]; // note: this fenwick tree is 1-indexed. ////PUโ€ PQ//////////////////////////////////////////////// ////// void fenwick_update(int pos, long long value) { while (pos <= N) { //cout<<"Fenwick Updating: "<<pos<<","<โ€ <value<<endl; ft[pos] += value; pos += pos&-pos; } } 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//////////////////////////////////////////////// ////// void fenwick_range_update(int pos_a, int pos_b, int val){ //TLE way Fenwick tree (cont) //for (int i=pos_a;i<=pos_b;i++){fenwick_updโ€ ate(i, val);} fenwick_update(pos_a, val); fenwick_update(pos_b+1, -val); } ////PURQ////////////// //////////////////////////////////////// long long fenwick_range_query(int pos_a, int pos_b) { return fenwick_query(pos_b) - fenwick_query(pโ€ os_a-1); } ////RUโ€ RQ//////////////////////////////////////////////// ////// long long B1[100 001 ];long long B2[100001]; void base_update(long long *ft, int pos, long long value){ //Add largest power of 2 dividing x / Last set bit in number x for (; pos <= N; pos += pos&(-pos)) ft[pos] += value; } void rurq_range_update(int a, int b,long long v){ base_update(B1, a, v); base_update(B1, b + 1, -v); base_update(B2, a, v * (a-1)); base_update(B2, b + 1, -v * b); } void rurq_point_update(int a, long long v){ rurq_range_update(a,a,v); } long long base_query(long long *ft,int b){ long long sum = 0; for(; b > 0; b -= b&(-b)) sum += ft[b]; return sum; } // Return sum A[1...b] long long rurq_query(int b){ By Hackin cheatography.com/hackin7/ Published 12th December, 2018. Last updated 27th December, 2019. Sponsored by CrosswordCheats.com Learn to solve cryptic crosswords!

by Hackin7 via cheatography.com/71996/cs/18253/

Deque deque d; // access an element / modify an element (0-indexed as well) - O(1) d[0] = 2; // change deque from {5, 10} to {2, 10} d[0]; // returns a value of 2 d.back(); // get back (last) element - O(1) d.front(); // get front (first) element - O(1) d.clear() // Remove all elements d.push_back(5); // add an element to the back - O(1) d.push_front(10); // add an element to the front - O(1) d.pop_back(); // remove the back (last) element - O(1) d.pop_front(); // remove the front (first) element

  • O(1) d.size(); //Return size d.empty // Whether queue is empty A stack and queue combined. ...or a vector that and be pushed and popped from the front as well. Deque = Double Ended Queue! 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; //Min value stored val = 0; lazyadd = 0; if (start!=end) { left = new node(start,mid); right = new node(mid+1,end); } } int value(){ if (start==end){ val += lazyadd;lazyadd = 0;return val; Segment Tree (cont) }else{ val += lazyadd; // Propagate Lazyadd right->lazyadd += lazyadd; left->lazyadd += lazyadd; lazyadd = 0; return val; } } void addRange(int lower_bound, int upperโ€ bound, int val_to_add){ if (start == lower_bound && end == upperโ€ bound){ lazyadd += val_to_add; }else{ if (lower_bound > mid){ right->addRange(lower_bound, upper_bound, val_to_add); }else if (upper_bound <= mid){ left->addRange(lower_bound, upper_bound, val_to_add); }else{ left->addRange(lower_bound, mid, val_to_add); right->addRange(mid+1, upperโ€ bound, val_to_add); } val = min(left->value(), right->vaโ€ lue()); } } // Update position to new_value // O(log N) void update(int pos, int new_val) { //position x to new value if (start==end) { val=new_val; return; } if (pos>mid) right->update(pos, new_val); if (pos<=mid) left->update(pos, new_val); val = min(left->val, right->val); } // Range Minimum Query // O(log N) By Hackin cheatography.com/hackin7/ Published 12th December, 2018. Last updated 27th December, 2019. Sponsored by CrosswordCheats.com Learn to solve cryptic crosswords!

by Hackin7 via cheatography.com/71996/cs/18253/

Segment Tree (cont) 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),right->rangeMinimumQuery(mid+1, upperโ€ bound)); } //Eโ€ nd////////////////////////////////////////// } } *root; void init(int N){ root = new node(0, N-1); // creates seg tree of size n } void update(int P, int V){ root->update(P,V); } int query(int A, int B){ int val = root->rangeMinimumQuery(A,B); return val; } By Hackin cheatography.com/hackin7/ Published 12th December, 2018. Last updated 27th December, 2019. Sponsored by CrosswordCheats.com Learn to solve cryptic crosswords!