C++ Cheatsheet
Tổng hợp Cheatsheet C++. Tóm tắt kiến thức C++ với các cú pháp và phương thức quan trọng.
🔖 Gợi ý từ Admin
📝 Tài liệu phỏng vấn kiến thức lập trình: Xem tại đây!!!
📌 Tìm hiểu về thuật toán: Xem tại đây!!!
📌 Roadmaps - Lộ trình trở thành một lập trình viên: Xem tại đây!!!
⚡️ Cheatsheet các ngôn ngữ lập trình: Xem tại đây!!!
⚡️ Handbook lập trình: Xem tại đây!!!
I. Tổng hợp Cheatsheet C++
1. Cơ bản
⚡️ Chạy 1 chương trình cpp đơn giản
#include <iostream>
int main() {
std::cout << "Hello world\n";
return 0;
}
// Biên dịch và chạy
$ g++ hello.cpp -o hello
$ ./hello
Hello world
⚡️ Biến (Variables)
int number = 5; // Integer
float f = 0.95; // Floating number
double PI = 3.14159; // Floating number
char yes = 'Y'; // Character
std::string s = "ME"; // String (text)
bool isRight = true; // Boolean
// Hằng (Constants)
const float RATE = 0.8;
int age {25}; // Since C++11
std::cout << age; // Print 25
⚡️ Kiểu dữ liệu nguyên thuỷ (Primitive Data Types)
| Kiểu dữ liệu | Kích thước (Size) | Phạm vi (Range) |
|---|---|---|
| int | 4 bytes | -231 đến 231-1 |
| float | 4 bytes | N/A |
| double | 8 bytes | N/A |
| char | 1 byte | -128 đến 127 |
| bool | 1 byte | true / false |
| void | N/A | N/A |
| wchar_t | 2 hoặc 4 bytes | độ rộng 1 ký tự |
⚡️ Đầu vào do người dùng nhập (User Input)
int num;
std::cout << "Nhập số: ";
std::cin >> num;
std::cout << "Bạn đã nhập " << num;
⚡️ Hoán đổi (Swap)
int a = 5, b = 10;
std::swap(a, b);
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;
⚡️ Bình luận (Comments)
// Comment 1 dòng
/*
Comment
nhiều dòng
*/
⚡️ Câu lệnh if (If statement)
if (a == 10) {
// làm gì đó ở đây
}
⚡️ Vòng lặp (Loops)
for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}
⚡️ Hàm (Functions)
#include <iostream>
void hello(); // Khai báo
int main() { // Hàm chính
hello(); // Gọi hàm
}
void hello() { // Định nghĩa hàm
std::cout << "Hello world!\n";
}
⚡️ Tham chiếu (References)
int i = 1;
int& ri = i; // ri là 1 tham chiếu tới i
ri = 2; // i bây giờ thay đổi thành 2
std::cout << "i=" << i;
i = 3; // i bây giờ thay đổi thành 3
std::cout << "ri=" << ri;
ri và i tham chiếu đến cùng một vị trí bộ nhớ.
⚡️ Namespaces: cho phép định danh toàn cầu (global) dưới một tên cụ thể
#include <iostream>
namespace ns1 {int val(){return 5;}}
int main()
{
std::cout << ns1::val();
}
#include <iostream>
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
cout << val();
}
2. Array (Mảng)
⚡️ Khai báo (Declaration)
std::array<int, 3> marks; // Định nghĩa
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Định nghĩa và khởi tạo
std::array<int, 3> = {92, 97, 98};
// Với phần tử rỗng
std::array<int, 3> marks = {92, 97};
std::cout << marks[2]; // Outputs: 0
⚡️ Các thao tác (Manipulation)
┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
0 1 2 3 4 5
std::array<int, 6> marks = {92, 97, 98, 99, 98, 94};
// In phần tử đầu tiên
std::cout << marks[0];
// Thay đổi phần tử thứ 2 thành 99
marks[1] = 99;
// Thay đổi đầu vào từ người dùng
std::cin >> marks[2];
⚡️ Hiển thị (Displaying)
char ref[5] = {'R', 'e', 'f'};
// Vòng lặp dựa trên phạm vi
for (const int &n : ref) {
std::cout << std::string(1, n);
}
// Vòng lặp truyền thống
for (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}
⚡️ Mảng 2 chiều (Multidimensional)
j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘
int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << " ";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1
3. Conditionals (Câu điều kiện)
⚡️ Mệnh đề if (If Clause)
if (a == 10) {
// xử lý ở đây nè...
}
int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even
⚡️ Câu lệnh else if (Else if Statement)
int score = 99;
if (score == 100) {
std::cout << "Superb";
}
else if (score >= 90) {
std::cout << "Excellent";
}
else if (score >= 80) {
std::cout << "Very Good";
}
else if (score >= 70) {
std::cout << "Good";
}
else if (score >= 60)
std::cout << "OK";
else
std::cout << "What?";
⚡️ Toán tử 3 ngôi (Ternary Operator)
┌── Đúng ──┐
K.quả = Đ.kiện ? B.thức1 : B.thức2;
└───── Sai ───────┘
int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;
int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;
⚡️ Câu lệnh switch (Switch Statement)
int num = 2;
switch (num) {
case 0:
std::cout << "Zero";
break;
case 1:
std::cout << "One";
break;
case 2:
std::cout << "Two";
break;
case 3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}
⚡️ Toán tử (Operators)
// Toán tử quan hệ (Relational Operators)
a == b // a bằng b
a != b // a khác b
a < b // a bé hơn b
a > b // a lớn hơn b
a <= b // a bé hơn hoặc bằng b
a >= b // a lớn hơn hoặc bằng b
// Toán tử gán (Assignment Operators)
a += b // được xem là a = a + b
a -= b // được xem là a = a - b
a *= b // được xem là a = a * b
a /= b // được xem là a = a / b
a %= b // được xem là a = a % b
// Toán tử logic (Logical Operators)
exp1 && exp2 // Cả 2 đều đúng (AND)
exp1 || exp2 // Đúng 1 trong 2 (OR)
!exp // Phủ định (NOT)
// Toán tử trên bit (Bitwise Operators)
a & b // Binary AND
a | b // Binary OR
a ^ b // Binary XOR
// ~ a Phần bù của nhị phân
a << b // Binary Shift Left
a >> b // Binary Shift Right
4. Loops (Vòng lặp)
⚡️ while
int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345
⚡️ do...while
int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345
⚡️ Câu lệnh continue (Continue statements)
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579
⚡️ Vòng lặp vô tận (Infinite loop)
while (true) { // true hoặc 1
std::cout << "Vô tận nè";
}
for (;;) {
std::cout << "Vô tận nè";
}
for(int i = 1; i > 0; i++) {
std::cout << "Vô tận nè";
}
⚡️ for_each (Since C++11)
#include <iostream>
int main()
{
auto print = [](int num) { std::cout << num << std::endl; };
std::array<int, 4> arr = {1, 2, 3, 4};
std::for_each(arr.begin(), arr.end(), print);
return 0;
}
⚡️ Range-based (Since C++11)
for (int n : {1, 2, 3, 4, 5}) {
std::cout << n << " ";
}
// Outputs: 1 2 3 4 5
std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << " ";
}
// Outputs: Q u i c k R e f . M E
⚡️ Câu lệnh break (Break statements)
int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}
⚡️ Biến thể (Several variations)
for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;
5. Functions (Hàm)
⚡️ Đối số và trả về (Arguments & Returns)
#include <iostream>
// Hàm add truyền 2 đối số int và trả về kiểu int
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(10, 20);
}
⚡️ Nạp chồng hàm (Overloading)
void fun(string a, string b) {
std::cout << a + " " + b;
}
void fun(string a) {
std::cout << a;
}
void fun(int a) {
std::cout << a;
}
⚡️ Hàm xây dựng sẵn (Built-in Functions)
#include <iostream>
#include <cmath> // import thư viện
int main() {
// sqrt() từ thư viện cmath
std::cout << sqrt(9);
}
6. Classes & Objects (Lớp và đối tượng)
⚡️ Định nghĩa lớp (Defining a Class)
class MyClass {
public: // Xác định cách truy cập
int myNum; // Thuộc tính (int variable)
string myString; // Thuộc tính (string variable)
};
⚡️ Tạo 1 đối tượng (Creating an Object)
MyClass myObj; // Tạo 1 đối tượng của lớp MyClass
myObj.myNum = 15; // Gán giá trị cho myNum là 15
myObj.myString = "Hello"; // Gán giá trị cho myString là "Hello"
cout << myObj.myNum << endl; // Output 15
cout << myObj.myString << endl; // Output "Hello"
⚡️ Hàm khởi tạo (Constructors)
class MyClass {
public:
int myNum;
string myString;
MyClass() { // Hàm khởi tạo
myNum = 0;
myString = "";
}
};
MyClass myObj; // Tạo 1 đối tượng của MyClass
cout << myObj.myNum << endl; // Output 0
cout << myObj.myString << endl; // Output ""
⚡️ Hàm huỷ (Destructors)
class MyClass {
public:
int myNum;
string myString;
MyClass() { // Hàm khởi tạo
myNum = 0;
myString = "";
}
~MyClass() { // Hàm huỷ
cout << "Đối tượng đã bị huỷ." << endl;
}
};
MyClass myObj; // Tạo 1 đối tượng của MyClass
// Code ở đây...
// Đối tượng tự động bị hủy khi chương trình thoát khỏi phạm vi.
⚡️ Phương thức lớp (Class Methods)
class MyClass {
public:
int myNum;
string myString;
void myMethod() { // Phương thức/hàm được định nghĩa bên trong lớp
cout << "Hello World!" << endl;
}
};
MyClass myObj; // Tạo 1 đối tượng của MyClass
myObj.myMethod(); // Gọi phương thức
⚡️ Quyền truy cập (Access Modifiers)
class MyClass {
public: // Truy cập công cộng
int x;
private: // Truy cập riêng tư
int y;
protected: // Truy cập bảo vệ
int z;
};
MyClass myObj;
myObj.x = 25; // Cho phép (public)
myObj.y = 50; // Không cho phép (private)
myObj.z = 75; // Không cho phép (protected)
⚡️ Getters and Setters
class MyClass {
private:
int myNum;
public:
void setMyNum(int num) { // Setter
myNum = num;
}
int getMyNum() { // Getter
return myNum;
}
};
MyClass myObj;
myObj.setMyNum(15); // Gán giá trị cho myNum là 15
cout << myObj.getMyNum() << endl; // Output 15
⚡️ Kế thừa (Inheritance)
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut!" << endl;
}
};
class Car : public Vehicle {
public:
string model = "Mustang";
};
Car myCar;
myCar.honk(); // Output "Tuut, tuut!"
cout << myCar.brand + " " + myCar.model << endl; // Output "Ford Mustang"
7. Preprocessor (Tiền xử lý)
⚡️ Preprocessor
- if
- elif
- else
- endif
- ifdef
- ifndef
- define
- undef
- include
- line
- error
- pragma
- defined
- __has_include
- __has_cpp_attribute
- export
- import
- module
⚡️ Includes
#include "iostream"
#include <iostream>
⚡️ Defines
#define FOO
#define FOO "hello"
#undef FOO
⚡️ If
#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif
⚡️ Error
#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif
⚡️ Macro
#define DEG(x) ((x) * 57.29)
⚡️ Token concat
#define DST(name) name##_s name##_t
DST(object); #=> object_s object_t;
⚡️ Stringification
#define STR(name) #name
char * a = STR(object); #=> char * a = "object";
⚡️ file and line
#define LOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")











