C++ 备忘单
# C++ 备忘单
提供基本语法和方法的 C++ 快速参考备忘单。
# 开始
# Hello.cpp
#include <iostream>
int main() {
std::cout << "Hello QuickRef\n";
return 0;
}
1
2
3
4
5
6
2
3
4
5
6
编译和运行
$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef
1
2
3
2
3
# 变量
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
// Constants
const float RATE = 0.8;
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
int age {25}; // Since C++11
std::cout << age; // Print 25
1
2
2
# 原始数据类型
数据类型 | 尺寸 | 范围 |
---|---|---|
int | 4字节 | -2 31 ~ 2 31 -1 |
float | 4字节 | 不适用 |
double | 8 字节 | 不适用 |
char | 1 字节 | -128 ~ 127 |
bool | 1 字节 | true / false |
void | 不适用 | 不适用 |
wchar_t | 2 或 4 个字节 | 1 个宽字符 |
# 用户输入
int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;
1
2
3
4
5
6
2
3
4
5
6
# 交换
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;
1
2
3
4
5
6
7
2
3
4
5
6
7
# 注释
// A single one line comment in C++
/* This is a multiple line comment
in C++ */
1
2
3
4
2
3
4
# if 语句
if (a == 10) {
// do something
}
1
2
3
2
3
# for 循环
for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}
1
2
3
2
3
# 函数
#include <iostream>
void hello(); // Declaring
int main() { // main function
hello(); // Calling
}
void hello() { // Defining
std::cout << "Hello QuickRef!\n";
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 参考
int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
ri
并i
引用相同的内存位置。
# 命名空间
#include <iostream>
namespace ns1 {int val(){return 5;}}
int main()
{
std::cout << ns1::val();
}
1
2
3
4
5
6
2
3
4
5
6
#include <iostream>
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
cout << val();
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
命名空间允许名称下的全局标识符
# C++ 数组
# 声明
int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initialize
int marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty members
int marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 操作
┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
0 1 2 3 4 5
1
2
3
4
2
3
4
int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 显示
char ref[5] = {'R', 'e', 'f'};
// Range based for loop
for (const int &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loop
for (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 多维数组
j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘
1
2
3
4
5
6
2
3
4
5
6
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
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# C++ 条件
# if 语句
if (a == 10) {
// do something
}
1
2
3
2
3
int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# Else if 语句
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?";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 运算符
# 关系运算符
a == b | a 等于 b |
---|---|
a != b | a 不等于 b |
a < b | a 小于 b |
a > b | a 更大 b |
a <= b | a 小于或等于 b |
a >= b | a 大于或等于 b |
# 赋值运算符
a += b | 又名 a = a + b |
---|---|
a -= b | 又名 a = a - b |
a *= b | 又名 a = a * b |
a /= b | 又名 a = a / b |
a %= b | 又名 a = a % b |
# 逻辑运算符
exp1 && exp2 | 两者都是真的*(AND)* |
---|---|
exp1 || exp2 | 要么为真*(或)* |
!exp | exp 是假的*(不是)* |
# 位运算符
a & b | 二进制与 |
---|---|
a | b | 二进制或 |
a ^ b | 二进制异或 |
a ~ b | 二进制补码 |
a << b | 二进制左移 |
a >> b | 二进制右移 |
# 三元运算符
┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘
1
2
3
2
3
int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;
1
2
3
4
5
2
3
4
5
int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Switch 语句
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# C++ 循环
# While
int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345
1
2
3
4
5
6
2
3
4
5
6
# Do-while
int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345
1
2
3
4
5
6
2
3
4
5
6
# Continue 语句
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579
1
2
3
4
5
6
2
3
4
5
6
# 无限循环
while (true) { // true or 1
std::cout << "infinite loop";
}
1
2
3
2
3
for (;;) {
std::cout << "infinite loop";
}
1
2
3
2
3
for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}
1
2
3
2
3
# for_each (从 C++11 版本开始)
#include <iostream>
void print(int num)
{
std::cout << num << std::endl;
}
int main()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Range-based (从 C++11 版本开始)
int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << " ";
}
// Outputs: 1 2 3 4 5
1
2
3
4
5
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
1
2
3
4
5
6
2
3
4
5
6
# Break 语句
int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 几种变体
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;
1
2
3
4
5
2
3
4
5
# C++ 函数
# 参数和返回
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(10, 20);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
add
是一个接受 2 个整数并返回整数的函数
# 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;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 内置函数
#include <iostream>
#include <cmath> // import library
int main() {
// sqrt() is from cmath
std::cout << sqrt(9);
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# C++ 预处理器
# 预处理器
- if (opens new window)
- elif (opens new window)
- else (opens new window)
- endif (opens new window)
- ifdef (opens new window)
- ifndef (opens new window)
- define (opens new window)
- undef (opens new window)
- include (opens new window)
- line (opens new window)
- error (opens new window)
- pragma (opens new window)
- defined (opens new window)
- __has_include (opens new window)
- __has_cpp_attribute (opens new window)
- export (opens new window)
- import (opens new window)
- module (opens new window)
# Includes 包括
#include "iostream"
#include <iostream>
1
2
2
# Defines 定义
#define FOO
#define FOO "hello"
#undef FOO
1
2
3
4
2
3
4
# If 如果
#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif
1
2
3
4
5
6
7
2
3
4
5
6
7
# Error 错误
#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif
1
2
3
4
2
3
4
# Macro 宏
#define DEG(x) ((x) * 57.29)
1
# Token concat 令牌连接
#define DST(name) name##_s name##_t
DST(object); #=> object_s object_t;
1
2
2
# Stringification 字符串化
#define STR(name) #name
char * a = STR(object); #=> char * a = "object";
1
2
2
# file and line 文件和行
#define LOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")
1
2
2
# 其他
# 转义序列
\b | 退格 |
---|---|
\f | 换页 |
\n | 换行 |
\r | 返回 |
\t | 水平标签 |
\v | 垂直标签 |
\\ | 反斜杠 |
\' | 单引号 |
\" | 双引号 |
\? | 问号 |
\0 | 空字符 |
# 关键词
- alignas (opens new window)
- alignof (opens new window)
- and (opens new window)
- and_eq (opens new window)
- asm (opens new window)
- atomic_cancel (opens new window)
- atomic_commit (opens new window)
- atomic_noexcept (opens new window)
- auto (opens new window)
- bitand (opens new window)
- bitor (opens new window)
- bool (opens new window)
- break (opens new window)
- case (opens new window)
- catch (opens new window)
- char (opens new window)
- char8_t (opens new window)
- char16_t (opens new window)
- char32_t (opens new window)
- class (opens new window)
- compl (opens new window)
- concept (opens new window)
- const (opens new window)
- consteval (opens new window)
- constexpr (opens new window)
- constinit (opens new window)
- const_cast (opens new window)
- continue (opens new window)
- co_await (opens new window)
- co_return (opens new window)
- co_yield (opens new window)
- decltype (opens new window)
- default (opens new window)
- delete (opens new window)
- do (opens new window)
- double (opens new window)
- dynamic_cast (opens new window)
- else (opens new window)
- enum (opens new window)
- explicit (opens new window)
- export (opens new window)
- extern (opens new window)
- false (opens new window)
- float (opens new window)
- for (opens new window)
- friend (opens new window)
- goto (opens new window)
- if (opens new window)
- inline (opens new window)
- int (opens new window)
- long (opens new window)
- mutable (opens new window)
- namespace (opens new window)
- new (opens new window)
- noexcept (opens new window)
- not (opens new window)
- not_eq (opens new window)
- nullptr (opens new window)
- operator (opens new window)
- or (opens new window)
- or_eq (opens new window)
- private (opens new window)
- protected (opens new window)
- public (opens new window)
- reflexpr (opens new window)
- register (opens new window)
- reinterpret_cast (opens new window)
- requires (opens new window)
- return (opens new window)
- short (opens new window)
- signed (opens new window)
- sizeof (opens new window)
- static (opens new window)
- static_assert (opens new window)
- static_cast (opens new window)
- struct (opens new window)
- switch (opens new window)
- synchronized (opens new window)
- template (opens new window)
- this (opens new window)
- thread_local (opens new window)
- throw (opens new window)
- true (opens new window)
- try (opens new window)
- typedef (opens new window)
- typeid (opens new window)
- typename (opens new window)
- union (opens new window)
- unsigned (opens new window)
- using (opens new window)
- virtual (opens new window)
- void (opens new window)
- volatile (opens new window)
- wchar_t (opens new window)
- while (opens new window)
- xor (opens new window)
- xor_eq (opens new window)
- final (opens new window)
- override (opens new window)
- transaction_safe (opens new window)
- transaction_safe_dynamic (opens new window)
# 另见
- C++ 信息图表和备忘录 (opens new window)(hackingcpp.com)
- C++ 参考 (opens new window) (cppreference.com)
- C++ 语言教程 (opens new window) (cplusplus.com)
编辑 (opens new window)