C++ 知识速查表
本页面汇总了 C++ 编程中最常用的语法和知识点,方便快速查阅。
基本语法
Hello World
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
命名空间
// 完整写法
std::cout << "hello" << std::endl;
// using 声明
using std::cout;
using std::endl;
cout << "hello" << endl;
// using 命名空间(慎用)
using namespace std;
auto 和 decltype
// auto 自动类型推导
auto x = 10; // int
auto y = 3.14; // double
auto& ref = x; // int&
const auto& cr = x; // const int&
// decltype 获取表达式类型
decltype(x) z = 20; // int
decltype((x)) r = x; // int&(注意双层括号)
数据类型
基本类型
| 类型 | 大小 | 说明 |
|---|---|---|
char | 1字节 | 字符 |
short | 2字节 | 短整数 |
int | 4字节 | 整数 |
long | 4/8字节 | 长整数 |
long long | 8字节 | 64位整数 |
float | 4字节 | 单精度浮点 |
double | 8字节 | 双精度浮点 |
bool | 1字节 | 布尔值 |
常用类型定义
#include <cstdint>
int8_t // 8位有符号整数
int16_t // 16位有符号整数
int32_t // 32位有符号整数
int64_t // 64位有符号整数
uint8_t // 8位无符号整数
size_t // 无符号整数(用于大小)
// auto 类型推导
auto a = 10; // int
auto b = 3.14; // double
类型转换
// 隐式转换
int a = 10;
double b = a; // int → double
// 显式转换(强制类型转换)
double c = 3.14;
int d = (int)c; // 3
int e = static_cast<int>(c); // 推荐
// 其他转换方式
const_cast<T> // 去除 const
reinterpret_cast<T> // 重新解释内存
dynamic_cast<T> // 运行时检查
数组和指针
数组
// 静态数组
int arr[5] = {1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3};
// 动态数组(C++11)
std::vector<int> vec = {1, 2, 3, 4, 5};
// 多维数组
int matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
指针
int value = 10;
int* ptr = &value; // 取地址
int val = *ptr; // 解引用
// 指针运算
ptr++; // 移动到下一个元素
ptr--; // 移动到上一个元素
// 空指针
int* p = nullptr;
引用
int value = 10;
int& ref = value; // 引用
ref = 20; // 修改原值
// 函数参数传递
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
控制流
条件语句
// if-else
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}
// switch
switch (value) {
case 1:
// code
break;
case 2:
// code
break;
default:
// code
}
// 三目运算符
int max = (a > b) ? a : b;
循环
// for 循环
for (int i = 0; i < 10; i++) {
// code
}
// 范围 for(C++11)
for (int x : arr) {
// code
}
// while
while (condition) {
// code
}
// do-while(至少执行一次)
do {
// code
} while (condition);
函数
函数定义
// 普通函数
int add(int a, int b) {
return a + b;
}
// 默认参数
void print(int n, int base = 10) {
// code
}
// 函数重载
int add(int a, int b);
double add(double a, double b);
// 模板函数
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// Lambda
auto lambda = [](int x) { return x * 2; };
参数传递
// 值传递
void func1(int value);
// 指针传递
void func2(int* ptr);
// 引用传递
void func3(int& ref);
// const 引用
void func4(const std::string& str);
类与对象
类定义
class Rectangle {
private:
double width;
double height;
public:
// 构造函数
Rectangle() : width(0), height(0) {}
Rectangle(double w, double h) : width(w), height(h) {}
// 成员函数
double area() const { return width * height; }
void setSize(double w, double h) {
width = w;
height = h;
}
// 析构函数
~Rectangle() {}
};
访问控制
class MyClass {
public: // 公有成员:任意访问
int publicMember;
private: // 私有成员:仅本类访问
int privateMember;
protected: // 保护成员:本类和派生类访问
int protectedMember;
};
特殊成员函数
class MyClass {
public:
// 构造函数
MyClass();
MyClass(int v);
// 拷贝构造函数
MyClass(const MyClass& other);
// 移动构造函数(C++11)
MyClass(MyClass&& other) noexcept;
// 拷贝赋值
MyClass& operator=(const MyClass& other);
// 移动赋值(C++11)
MyClass& operator=(MyClass&& other) noexcept;
// 析构函数
~MyClass();
};
运算符重载
class Complex {
private:
double real, imag;
public:
// 加法
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 输出流
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
};
继承与多态
继承
class Base {
public:
virtual void func() {}
};
class Derived : public Base {
public:
void func() override {} // 重写
};
// 使用多态
Base* ptr = new Derived();
ptr->func(); // 调用 Derived 的版本
虚函数
class Base {
public:
virtual void func() { // 虚函数
std::cout << "Base" << std::endl;
}
virtual ~Base() {} // 虚析构函数
};
class Derived : public Base {
public:
void func() override {
std::cout << "Derived" << std::endl;
}
};
纯虚函数与抽象类
class Shape {
public:
virtual double area() const = 0; // 纯虚函数
virtual ~Shape() = default;
};
// 抽象类不能实例化
// Shape s; // 错误!
class Circle : public Shape {
public:
double area() const override { return r * r * 3.14; }
};
STL 容器
顺序容器
std::vector<int> v; // 动态数组
std::deque<int> d; // 双端队列
std::list<int> l; // 双向链表
std::array<int, 5> a; // 固定数组
关联容器
std::set<int> s; // 集合
std::multiset<int> ms; // 多重集合
std::map<string, int> m; // 映射
std::multimap<string, int> mm; // 多重映射
// 无序容器(C++11)
std::unordered_set<int> us;
std::unordered_map<string, int> um;
容器操作
// 添加
v.push_back(1);
v.insert(v.begin(), 0);
// 删除
v.pop_back();
v.erase(v.begin());
// 访问
v[0];
v.at(0);
v.front();
v.back();
// 大小
v.size();
v.empty();
算法
常用算法
#include <algorithm>
// 排序
std::sort(v.begin(), v.end()); // 升序
std::sort(v.begin(), v.end(), std::greater<int>()); // 降序
// 查找
auto it = std::find(v.begin(), v.end(), 5);
auto it = std::binary_search(v.begin(), v.end(), 5); // 需要已排序
// 变换
std::transform(v.begin(), v.end(), v.begin(),
[](int x) { return x * 2; });
// 删除
v.erase(std::remove_if(v.begin(), v.end(),
[](int x) { return x % 2 == 0; }),
v.end());
智能指针
#include <memory>
// unique_ptr(独占所有权)
auto p1 = std::make_unique<int>(10);
std::unique_ptr<int> p2(new int(20));
// shared_ptr(共享所有权)
auto sp1 = std::make_shared<int>(30);
std::shared_ptr<int> sp2(sp1);
// weak_ptr(观察者)
std::weak_ptr<int> wp = sp1;
auto sp = wp.lock(); // 转为 shared_ptr
模板
函数模板
template<typename T>
T max(T a, T b) {
return a > b ? a : b;
}
// 调用
max(1, 2); // T = int
max(1.0, 2.0); // T = double
类模板
template<typename T>
class Stack {
private:
std::vector<T> data;
public:
void push(const T& item) { data.push_back(item); }
T pop() {
T item = data.back();
data.pop_back();
return item;
}
};
// 使用
Stack<int> s;
Stack<std::string> ss;
可变参数模板(C++11)
template<typename... Args>
void print(Args... args) {
((std::cout << args << " "), ...);
std::cout << std::endl;
}
Modern C++ 特性
auto 和 decltype
auto a = 10; // 自动推导类型
auto b = 3.14;
auto c = "hello";
decltype(a) d = 20; // 获取表达式类型
范围 for
for (int x : v) {
std::cout << x << " ";
}
// 使用引用修改
for (auto& x : v) {
x *= 2;
}
结构化绑定(C++17)
std::map<string, int> m;
for (const auto& [key, value] : m) {
std::cout << key << ": " << value << std::endl;
}
// 绑定 pair/tuple
auto [x, y] = std::make_pair(1, 2);
if constexpr(C++17)
template<typename T>
void print(const T& val) {
if constexpr (std::is_integral_v<T>) {
std::cout << "Integer: " << val << std::endl;
} else {
std::cout << "Other: " << val << std::endl;
}
}
concepts(C++20)
#include <concepts>
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
Numeric auto add(Numeric auto a, Numeric auto b) {
return a + b;
}
std::optional / variant / any(C++17)
#include <optional>
#include <variant>
#include <any>
// optional: 可能存在的值
std::optional<int> findValue(int key);
if (auto v = findValue(1)) {
std::cout << *v << std::endl;
}
// variant: 类型安全的联合体
std::variant<int, double, std::string> v;
v = 42;
std::cout << std::get<int>(v) << std::endl;
// any: 任意类型值
std::any a = 42;
std::cout << std::any_cast<int>(a) << std::endl;
std::string_view(C++17)
#include <string_view>
// 非拥有的字符串视图,避免拷贝
void process(std::string_view sv) {
std::cout << sv << std::endl;
}
process("hello"); // 不构造 string 对象
std::span(C++20)
#include <span>
// 对连续序列的非拥有视图
void process(std::span<int> s) {
for (int& n : s) n *= 2;
}
int arr[] = {1, 2, 3};
std::vector<int> vec = {1, 2, 3};
process(arr); // 都可接受
process(vec);
Ranges(C++20)
#include <ranges>
namespace rv = std::views;
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 过滤偶数并平方
auto result = nums
| rv::filter([](int n) { return n % 2 == 0; })
| rv::transform([](int n) { return n * n; });
for (int n : result) std::cout << n << " "; // 4 16 36 64 100
多线程
#include <thread>
#include <mutex>
#include <atomic>
// 创建线程
std::thread t([](){ /* code */ });
t.join(); // 等待结束
// 互斥锁
std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);
// 原子操作
std::atomic<int> counter(0);
counter.fetch_add(1);
异常处理
#include <stdexcept>
// 抛出异常
if (error) {
throw std::runtime_error("错误信息");
}
// 捕获异常
try {
riskyOperation();
} catch (const std::runtime_error& e) {
std::cerr << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "未知异常" << std::endl;
}
// noexcept 函数
void safeFunction() noexcept {
// 保证不抛出异常
}
标准异常类型
std::exception // 所有异常的基类
std::runtime_error // 运行时错误
std::logic_error // 逻辑错误
std::invalid_argument // 无效参数
std::out_of_range // 超出范围
std::bad_alloc // 内存分配失败
Lambda 表达式
// 基本语法
auto f = [](int x) { return x * 2; };
std::cout << f(5) << std::endl; // 10
// 捕获外部变量
int y = 10;
auto f1 = [y]() { return y; }; // 值捕获
auto f2 = [&y]() { y++; }; // 引用捕获
auto f3 = [=]() { return y; }; // 全部值捕获
auto f4 = [&]() { y++; }; // 全部引用捕获
// 泛型 Lambda(C++14)
auto add = [](auto a, auto b) { return a + b; };
add(1, 2); // int
add(1.5, 2.5); // double
// 用于 STL 算法
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
std::for_each(v.begin(), v.end(), [](int x) { std::cout << x << " "; });
右值引用与移动语义
#include <utility>
// 右值引用
int&& rref = 10;
// std::move:转换为右值引用
std::string s1 = "hello";
std::string s2 = std::move(s1); // 移动而非拷贝
// 移动构造函数
class MyClass {
public:
MyClass(MyClass&& other) noexcept {
// 窃取资源
}
MyClass& operator=(MyClass&& other) noexcept {
// 移动赋值
return *this;
}
};
// std::forward:完美转发
template<typename T>
void wrapper(T&& arg) {
process(std::forward<T>(arg));
}
输入输出
#include <iostream>
#include <fstream>
#include <sstream>
// 标准输入输出
std::cout << "输出" << std::endl;
std::cin >> value;
std::cerr << "错误" << std::endl;
// 文件操作
std::ofstream outFile("file.txt");
outFile << "写入内容" << std::endl;
std::ifstream inFile("file.txt");
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
// 字符串流
std::ostringstream oss;
oss << "数字: " << 42;
std::string result = oss.str();
std::istringstream iss("123 456");
int a, b;
iss >> a >> b;
格式化输出
#include <iomanip>
double pi = 3.14159265358979;
// 精度
std::cout << std::setprecision(3) << pi << std::endl; // 3.142
// 宽度
std::cout << std::setw(10) << 42 << std::endl; // " 42"
// 对齐
std::cout << std::left << std::setw(10) << 42 << std::endl; // "42 "
// 填充
std::cout << std::setfill('0') << std::setw(5) << 42 << std::endl; // "00042"
// 进制
std::cout << std::hex << 255 << std::endl; // "ff"
std::cout << std::oct << 255 << std::endl; // "377"
常见错误
内存泄漏
// 错误
int* p = new int(10);
// 忘记 delete
// 正确:使用智能指针
auto p = std::make_unique<int>(10);
悬空指针
// 错误
int* p = new int(10);
delete p;
*p = 20; // 访问已释放的内存
// 正确:delete 后置空
int* p = new int(10);
delete p;
p = nullptr;
循环引用
// 使用 weak_ptr 打破循环引用
class Node {
public:
std::weak_ptr<Node> next;
std::weak_ptr<Node> prev;
};
常用头文件
#include <iostream> // 输入输出
#include <vector> // 动态数组
#include <string> // 字符串
#include <algorithm> // 算法
#include <memory> // 智能指针
#include <thread> // 线程
#include <mutex> // 互斥锁
#include <map> // 映射
#include <set> // 集合
#include <functional> // 函数对象
#include <cmath> // 数学函数