Skip to content

Instantly share code, notes, and snippets.

@charlires
Last active July 13, 2021 17:57
Show Gist options
  • Save charlires/0b94399bf73c7a01cc92b86c2e49cd64 to your computer and use it in GitHub Desktop.
Save charlires/0b94399bf73c7a01cc92b86c2e49cd64 to your computer and use it in GitHub Desktop.
C++ CheatSheet

Data Structures in CPP

MAP

// Init
map<char, int> m = {
    {'1', 1},
    {'2', 2},
    {'3', 3},
    {'4', 4},
};

// insert 
m['h'] = 1;
m.insert(pair<char, int>('h', 2));

// Erase
m.erase('h');
    
// Itearate
// map<char, int>::iterator itr = m.begin()
for (auto itr = m.begin(); itr != m.end(); ++itr)
{
    // (*itr).first == itr->first
    cout << itr->first << endl;
}

// Find 
// map<char, int>::iterator itr;
auto it = m.find('3');
if (it != m.end())
    cout << it->first <<  it->second << endl;

QUEUE

// Init
queue<int> q;

// Insert
q.push(1);

// Erase first
q.pop();

// Iterate
// q.size()
// q.front() 
// q.back()
while (!q.empty())
{
    cout << q.front() << " ";
    q.pop();
}

STACK

// Init
stack<int> s;

// Insert
s.push(1);

// Erase last
s.pop();

// Iterate
// s.size()
// s.top()
// s.back()
while (!s.empty())
{
    cout << s.top() << " ";
    s.pop();
}

SET

// Init
set<char> s = {'C', 'D'};

// Insert
s.insert('A');

// Erase
s.erase('C');

// Find
if (s.find('C') != s.end())
{
    cout << "Found C!" << endl;
}

// Iterate
for (auto itr = s.begin(); itr != s.end(); ++itr)
{
    cout << *itr << endl;
}

VECTOR

// Init
vector<int> v1 = {1, 2, 3};

// Insert
v1.push_back(4);
v1.insert(v1.begin(), 0);
v1.insert(v1.end(), 5);

auto it = next(v1.begin(), 2);
v1.insert(it, 8);

// Erase
v1.pop_back();
v1.erase(v1.begin());

// Iterate
// v1.size()
for (int i = 0; i < v1.size(); i++)
{
    cout << v1[i] << endl;
}

for (auto itr = v1.begin(); itr != v1.end(); ++itr)
{
    cout << *itr << endl;
}

Pointers

int x = 5;

&x reference of x (e.g. 0x123AB)

Assign variable by reference (this works for function args too void foo(int &y) {})

int &y = x;

y now reference x (both points to the same memory location)

y = 3;

Assing 3 in y will affect x (now x == 3)

Pointers can only store references to variables

int *ptr = &x; 
// or
int *ptr = &y;

ptr referece of x (e.g. 0x123AB)

&ptr reference of ptr (e.g. 0xABCDF)

*ptr value of x (e.g. 3)

*ptr = 10;

Assing 10 in *ptr will affect x (now x == 10)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment