Skip to content

Cheat Sheet - Tóm tắt nhanh C++

📋 Cú pháp cơ bản

Include và Namespace

cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;

Khai báo biến

cpp
int so_nguyen = 42;
double so_thuc = 3.14;
char ky_tu = 'A';
string chuoi = "Hello";
bool dieu_kien = true;

Mảng và Vector

cpp
// Mảng tĩnh
int arr[5] = {1, 2, 3, 4, 5};

// Vector
vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);
vec.pop_back();

🔄 Cấu trúc điều khiển

If-else

cpp
if (condition) {
    // code
} else if (other_condition) {
    // code
} else {
    // code
}

Vòng lặp

cpp
// For loop
for (int i = 0; i < n; i++) {
    // code
}

// Range-based for
for (auto& item : container) {
    // code
}

// While
while (condition) {
    // code
}

Switch

cpp
switch (variable) {
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    default:
        // code
}

⚙️ Hàm

Khai báo hàm

cpp
// Hàm cơ bản
int cong(int a, int b) {
    return a + b;
}

// Pass by reference
void doi_gia_tri(int& x) {
    x = 100;
}

// Default parameters
void ham_mac_dinh(int a, int b = 10) {
    // code
}

Lambda functions

cpp
auto lambda = [](int x) -> int {
    return x * 2;
};

// Với capture
int multiplier = 3;
auto lambda2 = [multiplier](int x) {
    return x * multiplier;
};

🏗 OOP

Class cơ bản

cpp
class MyClass {
private:
    int private_var;
    
public:
    // Constructor
    MyClass(int val) : private_var(val) {}
    
    // Destructor
    ~MyClass() {}
    
    // Getter/Setter
    int get_value() const { return private_var; }
    void set_value(int val) { private_var = val; }
    
    // Virtual function
    virtual void do_something() = 0;
};

Inheritance

cpp
class Derived : public Base {
public:
    void do_something() override {
        // implementation
    }
};

📚 STL Containers

Vector

cpp
vector<int> v = {1, 2, 3};
v.push_back(4);
v.pop_back();
v.size();
v[0];  // Truy cập

List

cpp
list<int> l = {1, 2, 3};
l.push_front(0);
l.push_back(4);
l.pop_front();

Stack

cpp
stack<int> s;
s.push(1);
s.push(2);
int top = s.top();
s.pop();

Queue

cpp
queue<int> q;
q.push(1);
q.push(2);
int front = q.front();
q.pop();

Set

cpp
set<int> s = {3, 1, 4, 1, 5};  // {1, 3, 4, 5}
s.insert(2);
s.erase(3);
s.find(4) != s.end();  // Tìm kiếm

Map

cpp
map<string, int> m;
m["key"] = 42;
m.insert({"key2", 100});
m.find("key") != m.end();

🔧 STL Algorithms

Sorting

cpp
sort(vec.begin(), vec.end());
sort(vec.rbegin(), vec.rend());  // Giảm dần

Searching

cpp
auto it = find(vec.begin(), vec.end(), value);
bool found = binary_search(vec.begin(), vec.end(), value);

Modifying

cpp
copy(src.begin(), src.end(), dest.begin());
transform(vec.begin(), vec.end(), vec.begin(), [](int x) { return x * 2; });
remove_if(vec.begin(), vec.end(), [](int x) { return x < 0; });

🔗 Pointers & References

Pointers

cpp
int x = 42;
int* ptr = &x;
int value = *ptr;  // Dereference

// Dynamic memory
int* arr = new int[10];
delete[] arr;

References

cpp
int x = 42;
int& ref = x;  // Reference to x
ref = 100;     // x is now 100

Smart Pointers

cpp
#include <memory>

unique_ptr<int> ptr = make_unique<int>(42);
shared_ptr<int> shared = make_shared<int>(42);

⚠️ Exception Handling

cpp
try {
    // Risky code
    if (error_condition) {
        throw runtime_error("Error message");
    }
} catch (const runtime_error& e) {
    cout << "Error: " << e.what() << endl;
} catch (...) {
    cout << "Unknown error" << endl;
}

📝 Templates

Function Template

cpp
template<typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

Class Template

cpp
template<typename T>
class Container {
private:
    T data;
public:
    Container(T val) : data(val) {}
    T get() const { return data; }
};

🔢 Common Patterns

Iteration

cpp
// C++11 range-based for
for (const auto& item : container) {
    // process item
}

// Traditional iterator
for (auto it = container.begin(); it != container.end(); ++it) {
    // process *it
}

Resource Management (RAII)

cpp
class FileHandler {
    FILE* file;
public:
    FileHandler(const char* filename) {
        file = fopen(filename, "r");
    }
    ~FileHandler() {
        if (file) fclose(file);
    }
};

Initialization

cpp
// C++11 uniform initialization
vector<int> vec{1, 2, 3, 4, 5};
MyClass obj{param1, param2};

// C++14 auto return type
auto func() {
    return 42;  // Type deduced as int
}

🚀 Modern C++ Features

Auto keyword

cpp
auto x = 42;        // int
auto y = 3.14;      // double
auto z = "hello";   // const char*

Range-based for

cpp
vector<int> vec = {1, 2, 3, 4, 5};
for (auto x : vec) {
    cout << x << " ";
}

nullptr

cpp
int* ptr = nullptr;  // Better than NULL

constexpr

cpp
constexpr int factorial(int n) {
    return (n <= 1) ? 1 : n * factorial(n - 1);
}

🎯 Best Practices

  1. Sử dụng const khi có thể
  2. Prefer references over pointers
  3. Sử dụng RAII cho resource management
  4. Avoid raw pointers, sử dụng smart pointers
  5. Sử dụng range-based for khi có thể
  6. Initialize variables khi khai báo
  7. Sử dụng STL thay vì implement từ đầu

🐛 Common Mistakes

  1. Array bounds checking
  2. Memory leaks (forget delete)
  3. Uninitialized variables
  4. Iterator invalidation
  5. Dangling pointers
  6. Buffer overflow

📚 Useful Headers

cpp
#include <iostream>     // I/O operations
#include <vector>       // Dynamic arrays
#include <string>       // String class
#include <algorithm>    // STL algorithms
#include <memory>       // Smart pointers
#include <fstream>      // File I/O
#include <map>          // Map container
#include <set>          // Set container
#include <queue>        // Queue and priority_queue
#include <stack>        // Stack container

Khóa học C++ miễn phí