This is an old revision of the document!
Coding Cheat Sheet
For general techniques, see Algorithm Techniques.
For explanations of problems see Algorithm Problems.
Strings
Length of a string:
C++:
stringVar.length()
Adding a character to a string: c++:
// Appending the string. init.append(add); // concatenating the string. strcat(init, add); // Appending the string. init = init + add;
To convert anything into a string use to_string()
.
To erase characters, we use string.erase(pos, len)
.
To convert to upper case or lower case you have to iterate over every character
and use tolower(int c)
or toupper(int c)
. They return the case converted
character.
To check if a character is alphanumeric (letters and numbers) or just alphabetic:
isalnum(int c) // alpha numeric isalpha(int c) // alphabetic
Returns false (0) if not.
Maps
Iterating over a map and deleting an element
This is tricky! The following does NOT work!!
for(auto& entry : dm) { if( dm.find(entry.second) == dm.end() ) { dm.erase(entry.first); changed = true; } }
Use a regular for loop with constant interators.
for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */) { if (must_delete) { m.erase(it++); // or "it = m.erase(it)" since C++11 } else { ++it; } }
Removing Whitespace from a string
s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());
String to Number
you can use
std::stoi( str )
where str is your number as std::string
.
There are version for all flavours of numbers: long stol(string), float stof(string), double stod(string),… see http://en.cppreference.com/w/cpp/string/basic_string/stol
Vectors
Sorting a 2D Vector
To make a sorting function do as follows. Remember, it means what has to be true for v1 to go before v2.
bool sortFunc(const vector<int> &v1, const vector<int> &v2) { return v1[0] < v2[0]; }
Or with a lambda:
sort(in.begin(), in.end(), [] (vector<int> &a, vector<int> &b) {return a[0] < b[0];});
Initialize 2D Vector
Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value.
vector<vector<int>> nums(NUMBER_OF_ROWS, vector<int>(NUMBER_OF_COLS, 0) );
Unordered Set
An ordered set of unique numbers that are stored by a key, which is equal to the number in each element. They are not ordered and allow for the fast retrieval and insertion of each element (constant time O(1)). To make them you use the following syntax:
#include <unordered_set> std::unordered_set<int> my_set; my_set.insert(12); std::unordered_set<int>::iterator it = my_set.find(13); if(it == my_set.end()) { std::cout << "13 not found!" << std::endl; } else { std::cout << "Found: " << it* << std::endl; // Erase it: my_set.erase(it); // my_set.erase(13); // you can erase by iterator or by key, the function will return 0 or 1 depending on if erased. }
Queue
A queue is just a line man. First in fist out. You can only remove the element in the front of the line of a queue. Remember that!
pop()
- pops front of the queue, does NOT return the element!push()
- pushes an element to the back of the queue.front()
- reference to element in the front of the queue.back()
- reference to the elemnt in the back of the queue.size()
empty()
- returns whether empty or not.
Ordered Container Order
In C++ associative containers such as sets and maps store values in ascending order. You can easily change this by passing a comparative function that takes in two parameters a and b and returns true if a goes before b. STL provides basic versions of these functions for you!
// Here if greater<int> is used to make // sure that elements are stored in // descending order of keys. map<int, string, greater <int> > mymap;
Range Based Loops
Range based loops return copies unless a reference is requested. They return the pair, so no pointer member access required.
unordered_map<int, int> counts; multimap<int,int, greater<int>> sorted; for(auto& i : counts) { sorted.insert(make_pair(i.second, i.first)); } vector<int> out; for(auto& i : sorted) { out.push_back(i.second); if(--k == 0) break; }