This is an old revision of the document!


Coding Cheat Sheet

For general techniques, see Algorithm Techniques.

For explanations of problems see Algorithm Problems.

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).

Sorting a 2D Vector

To make a sorting function do as follows:

bool sortFunc(const vector<int> &v1, const vector<int> &v2)
{
  return v1[0] < v2[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) );

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.
}

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!

  1. pop() - pops front of the queue, does NOT return the element!
  2. push() - pushes an element to the back of the queue.
  3. front() - reference to element in the front of the queue.
  4. back() - reference to the elemnt in the back of the queue.
  5. size()
  6. empty() - returns whether empty or not.

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 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;
}
  • coding_cheat_sheet.1597798539.txt.gz
  • Last modified: 2020/08/19 00:55
  • by 127.0.0.1