c++大全
2026-02-22 14:31:32
发布于:湖北
// ==================== 标准C库头文件 ====================
// 输入输出
#include <stdio.h> // 标准输入输出
#include <conio.h> // 控制台输入输出(非标准)
#include <io.h> // 文件底层操作
// 字符串处理
#include <string.h> // 字符串处理函数
#include <strings.h> // 字符串比较(BSD)
#include <ctype.h> // 字符处理函数
#include <wchar.h> // 宽字符处理
#include <wctype.h> // 宽字符分类
// 数学函数
#include <math.h> // 数学函数
#include <complex.h> // 复数运算
#include <tgmath.h> // 类型通用数学
#include <fenv.h> // 浮点环境
#include <float.h> // 浮点数特性
// 内存管理
#include <stdlib.h> // 内存分配(malloc, free)和rand(), abs()等
#include <alloca.h> // 栈内存分配
#include <malloc.h> // 内存分配调试
// 时间和日期
#include <time.h> // 时间和日期
#include <sys/time.h> // 高精度时间(Unix)
#include <sys/times.h> // 进程时间
// 文件系统
#include <sys/stat.h> // 文件状态
#include <sys/types.h> // 系统数据类型
#include <dirent.h> // 目录操作
#include <unistd.h> // Unix标准函数
#include <fcntl.h> // 文件控制
#include <errno.h> // 错误码
// 系统和进程
#include <signal.h> // 信号处理
#include <setjmp.h> // 非局部跳转
#include <sys/wait.h> // 进程等待
#include <sys/ipc.h> // 进程间通信
#include <sys/shm.h> // 共享内存
#include <sys/msg.h> // 消息队列
#include <sys/sem.h> // 信号量
#include <pthread.h> // POSIX线程
// ==================== C++标准库头文件 ====================
// 标准模板库(STL)基础
#include <iostream> // 标准输入输出流
#include <iomanip> // 输入输出操纵符
#include <fstream> // 文件输入输出流
#include <sstream> // 字符串流
#include <string> // 字符串类
// 容器(Containers)
#include <vector> // 动态数组
#include <list> // 双向链表
#include <deque> // 双端队列
#include <queue> // 队列
#include <stack> // 栈
#include <set> // 集合
#include <map> // 映射
#include <unordered_set> // 哈希集合
#include <unordered_map> // 哈希映射
#include <array> // 固定数组
#include <forward_list> // 单向链表
#include <bitset> // 位集
#include <tuple> // 元组
// 算法(Algorithms)
#include <algorithm> // 算法函数
#include <numeric> // 数值算法
#include <functional> // 函数对象
#include <iterator> // 迭代器
// 多线程(Concurrency)
#include <thread> // 线程
#include <mutex> // 互斥锁
#include <condition_variable> // 条件变量
#include <future> // 异步任务
#include <atomic> // 原子操作
// 智能指针和内存
#include <memory> // 智能指针
#include <new> // new运算符
#include <scoped_allocator> // 作用域分配器
// 时间和日期
#include <chrono> // 时间库
#include <ctime> // C风格时间
#include <ratio> // 编译期比例
// 正则表达式
#include <regex> // 正则表达式
// 随机数
#include <random> // 随机数生成
// 文件系统
#include <filesystem> // 文件系统(C++17)
// 输入输出扩展
#include <ios> // 输入输出基础
#include <iosfwd> // 输入输出前向声明
#include <streambuf> // 流缓冲区
#include <istream> // 输入流
#include <ostream> // 输出流
// 数值和数学
#include <complex> // 复数
#include <valarray> // 数值数组
#include <numbers> // 数学常数(C++20)
#include <bit> // 位操作(C++20)
#include <cmath> // C风格数学
// 类型支持
#include <typeinfo> // 类型信息
#include <typeindex> // 类型索引
#include <type_traits> // 类型特性
#include <cstddef> // 标准定义
#include <cstdint> // 固定宽度整数
#include <limits> // 数值极限
#include <climits> // C整数限制
#include <cfloat> // C浮点限制
// 异常处理
#include <exception> // 异常类
#include <stdexcept> // 标准异常
#include <cassert> // 断言
#include <cerrno> // C错误码
// 国际化
#include <locale> // 本地化
#include <codecvt> // 代码转换
#include <clocale> // C本地化
// 其他实用工具
#include <utility> // 实用工具
#include <optional> // 可选值(C++17)
#include <variant> // 变体(C++17)
#include <any> // 任意类型(C++17)
#include <string_view> // 字符串视图(C++17)
#include <span> // 连续序列视图(C++20)
#include <expected> // 预期值(C++23)
#include <source_location> // 源码位置(C++20)
#include <version> // 库版本信息
#include <initializer_list> // 初始化列表
// ==================== 平台特定头文件 ====================
// Windows
#include <windows.h> // Windows API
#include <winsock2.h> // Windows Socket
#include <ws2tcpip.h> // Windows Socket扩展
#include <process.h> // 进程和线程
#include <direct.h> // 目录操作
// Linux/Unix
#include <unistd.h> // POSIX API
#include <sys/socket.h> // Socket API
#include <netinet/in.h> // Internet地址族
#include <arpa/inet.h> // Internet操作
#include <netdb.h> // 网络数据库操作
#include <dlfcn.h> // 动态链接
#include <sys/mman.h> // 内存管理
#include <sys/ioctl.h> // 设备控制
#include <sys/epoll.h> // I/O事件通知
#include <sys/select.h> // 同步I/O复用
#include <sys/poll.h> // 事件轮询
#include <sys/sysinfo.h> // 系统信息
#include <sys/utsname.h> // 系统名称
#include <sys/resource.h> // 资源使用
// ==================== 图形和GUI库 ====================
// 简单图形
#include <graphics.h> // Borland图形库
#include <glut.h> // OpenGL实用工具
#include <GL/gl.h> // OpenGL
#include <GL/glu.h> // OpenGL实用库
#include <GL/glfw3.h> // GLFW窗口库
#include <SDL2/SDL.h> // SDL2
#include <SFML/Graphics.hpp> // SFML
// GUI框架
#include <QApplication> // Qt
#include <QWidget>
#include <QMainWindow>
#include <wx/wx.h> // wxWidgets
#include <gtk/gtk.h> // GTK+
// ==================== 数据库 ====================
#include <mysql/mysql.h> // MySQL
#include <sqlite3.h> // SQLite
#include <postgresql/libpq-fe.h> // PostgreSQL
#include <oci.h> // Oracle OCI
// ==================== 网络编程 ====================
#include <curl/curl.h> // libcurl
#include <boost/asio.hpp> // Boost.Asio
#include <mongoose.h> // Mongoose
#include <cpprest/http_client.h> // C++ REST SDK
// ==================== 压缩和序列化 ====================
#include <zlib.h> // zlib压缩
#include <lz4.h> // LZ4压缩
#include <boost/archive/text_oarchive.hpp> // Boost序列化
#include <cereal/cereal.hpp> // Cereal序列化
// ==================== 日志和调试 ====================
#include <glog/logging.h> // Google Log
#include <spdlog/spdlog.h> // spdlog
#include <boost/log/trivial.hpp> // Boost Log
#include <debugapi.h> // Windows调试
// ==================== 科学计算 ====================
#include <eigen3/Eigen/Dense> // Eigen
#include <armadillo> // Armadillo
#include <boost/numeric/ublas/matrix.hpp> // Boost.uBLAS
#include <fftw3.h> // FFTW
#include <gsl/gsl_matrix.h> // GSL
// ==================== C兼容的C++头文件 ====================
#include <cstdio> // 对应stdio.h
#include <cstdlib> // 对应stdlib.h
#include <cstring> // 对应string.h
#include <cmath> // 对应math.h
#include <ctime> // 对应time.h
#include <cctype> // 对应ctype.h
#include <cstdarg> // 对应stdarg.h
#include <cstddef> // 对应stddef.h
#include <cstdint> // 对应stdint.h
#include <climits> // 对应limits.h
#include <cfloat> // 对应float.h
#include <cassert> // 对应assert.h
#include <cerrno> // 对应errno.h
#include <csignal> // 对应signal.h
#include <csetjmp> // 对应setjmp.h
#include <clocale> // 对应locale.h
using namespace std;
// 判断素数
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
// 最大公约数
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// 最小公倍数
int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
// 阶乘
long long factorial(int n) {
long long result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
2. 字符串处理函数
cpp
// 字符串分割
vector<string> split(const string & s, char delimiter) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
// 字符串转大写
string toUpper(string str) {
transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
}
// 去除字符串首尾空格
string trim(const string& str) {
size_t first = str.find_first_not_of(" \t\n\r");
if (first == string::npos) return "";
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, last - first + 1);
}
3. 数组 / 容器操作函数
cpp
// 打印数组
template<typename T>
void printArray(const vector<T>&arr) {
for (const auto& elem : arr) {
cout << elem << " ";
}
cout << endl;
}
// 数组求和
template<typename T>
T sumArray(const vector<T>& arr) {
T sum = 0;
for (const auto& elem : arr) {
sum += elem;
}
return sum;
}
// 查找最大值索引
template<typename T>
int findMaxIndex(const vector<T>& arr) {
return max_element(arr.begin(), arr.end()) - arr.begin();
}
4. 文件操作函数
cpp
// 读取文件到字符串
string readFile(const string & filename) {
ifstream file(filename);
if (!file.is_open()) return "";
string content((istreambuf_iterator<char>(file)),
istreambuf_iterator<char>());
return content;
}
// 写入文件
bool writeFile(const string& filename, const string& content) {
ofstream file(filename);
if (!file.is_open()) return false;
file << content;
return true;
}
5. 验证 / 检查函数
cpp
// 验证邮箱格式
bool isValidEmail(const string & email) {
const regex pattern(R"((\w+)(\.\w+)*@(\w+)(\.\w+)+)");
return regex_match(email, pattern);
}
// 验证手机号(简单版)
bool isValidPhone(const string& phone) {
if (phone.length() != 11) return false;
return all_of(phone.begin(), phone.end(), ::isdigit);
}
6. 排序和搜索函数
cpp
// 自定义排序(按绝对值)
bool absCompare(int a, int b) {
return abs(a) < abs(b);
}
// 二分查找(递归版)
int binarySearch(const vector<int>& arr, int left, int right, int target) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] > target)
return binarySearch(arr, left, mid - 1, target);
return binarySearch(arr, mid + 1, right, target);
}
return -1;
}
7. 类和对象相关函数
cpp
class Student {
private:
string name;
int age;
vector<double> scores;
public:
// 构造函数
Student(string n, int a) : name(n), age(a) {}
// Getter/Setter
string getName() const { return name; }
void setName(const string& n) { name = n; }
// 计算平均分
double getAverageScore() const {
if (scores.empty()) return 0.0;
double sum = accumulate(scores.begin(), scores.end(), 0.0);
return sum / scores.size();
}
// 添加成绩
void addScore(double score) {
scores.push_back(score);
}
// 运算符重载
bool operator<(const Student& other) const {
return getAverageScore() < other.getAverageScore();
}
};
8. 日期时间函数
cpp
// 判断闰年
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 获取当前时间字符串
string getCurrentTime() {
auto now = chrono::system_clock::now();
time_t time = chrono::system_clock::to_time_t(now);
return ctime(&time);
}
9. 随机数生成
cpp
// 生成指定范围内的随机整数
int randomInt(int min, int max) {
static random_device rd;
static mt19937 gen(rd());
uniform_int_distribution<> dist(min, max);
return dist(gen);
}
// 生成随机字符串
string randomString(int length) {
static const string chars =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string result;
for (int i = 0; i < length; i++) {
result += chars[randomInt(0, chars.length() - 1)];
}
return result;
}
10. 内存管理函数
cpp
// 安全的数组创建和释放
template<typename T>
T * createArray(size_t size) {
return new T[size]();
}
template<typename T>
void safeDelete(T*& ptr) {
if (ptr != nullptr) {
delete ptr;
ptr = nullptr;
}
}
template<typename T>
void safeDeleteArray(T*& ptr) {
if (ptr != nullptr) {
delete[] ptr;
ptr = nullptr;
}
}
这些函数涵盖了日常C++编程中最常见的需求,是每个C++程序员都应该掌握的基本工具函数。您可以根据具体项目需求进行修改和扩展。
把他们放到一起
以下是整合在一起的完整C++代码,包含所有经典的自定义函数:
cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <fstream>
#include <iterator>
#include <regex>
#include <cmath>
#include <numeric>
#include <random>
#include <chrono>
#include <ctime>
using namespace std;
// ==================== 1. 基础工具函数 ====================
// 判断素数
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
// 最大公约数
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// 最小公倍数
int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
// 阶乘
long long factorial(int n) {
long long result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
// ==================== 2. 字符串处理函数 ====================
// 字符串分割
vector<string> split(const string& s, char delimiter) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
// 字符串转大写
string toUpper(string str) {
transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
}
// 去除字符串首尾空格
string trim(const string& str) {
size_t first = str.find_first_not_of(" \t\n\r");
if (first == string::npos) return "";
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, last - first + 1);
}
// ==================== 3. 数组/容器操作函数 ====================
// 打印数组
template<typename T>
void printArray(const vector<T>& arr) {
for (const auto& elem : arr) {
cout << elem << " ";
}
cout << endl;
}
// 数组求和
template<typename T>
T sumArray(const vector<T>& arr) {
T sum = 0;
for (const auto& elem : arr) {
sum += elem;
}
return sum;
}
// 查找最大值索引
template<typename T>
int findMaxIndex(const vector<T>& arr) {
return max_element(arr.begin(), arr.end()) - arr.begin();
}
// ==================== 4. 文件操作函数 ====================
// 读取文件到字符串
string readFile(const string& filename) {
ifstream file(filename);
if (!file.is_open()) return "";
string content((istreambuf_iterator<char>(file)),
istreambuf_iterator<char>());
return content;
}
// 写入文件
bool writeFile(const string& filename, const string& content) {
ofstream file(filename);
if (!file.is_open()) return false;
file << content;
return true;
}
// ==================== 5. 验证/检查函数 ====================
// 验证邮箱格式
bool isValidEmail(const string& email) {
const regex pattern(R"((\w+)(\.\w+)*@(\w+)(\.\w+)+)");
return regex_match(email, pattern);
}
// 验证手机号(简单版)
bool isValidPhone(const string& phone) {
if (phone.length() != 11) return false;
return all_of(phone.begin(), phone.end(), ::isdigit);
}
// ==================== 6. 排序和搜索函数 ====================
// 自定义排序(按绝对值)
bool absCompare(int a, int b) {
return abs(a) < abs(b);
}
// 二分查找(递归版)
int binarySearch(const vector<int>& arr, int left, int right, int target) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] > target)
return binarySearch(arr, left, mid - 1, target);
return binarySearch(arr, mid + 1, right, target);
}
return -1;
}
// ==================== 7. 类和对象相关函数 ====================
class Student {
private:
string name;
int age;
vector<double> scores;
public:
// 构造函数
Student() : name(""), age(0) {}
Student(string n, int a) : name(n), age(a) {}
// Getter/Setter
string getName() const { return name; }
void setName(const string& n) { name = n; }
int getAge() const { return age; }
void setAge(int a) { age = a; }
// 计算平均分
double getAverageScore() const {
if (scores.empty()) return 0.0;
double sum = accumulate(scores.begin(), scores.end(), 0.0);
return sum / scores.size();
}
// 添加成绩
void addScore(double score) {
scores.push_back(score);
}
// 获取所有成绩
vector<double> getScores() const { return scores; }
// 运算符重载
bool operator<(const Student& other) const {
return getAverageScore() < other.getAverageScore();
}
// 打印学生信息
void printInfo() const {
cout << "姓名: " << name << ", 年龄: " << age
<< ", 平均分: " << getAverageScore() << endl;
}
};
// ==================== 8. 日期时间函数 ====================
// 判断闰年
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 获取当前时间字符串
string getCurrentTime() {
auto now = chrono::system_clock::now();
time_t time = chrono::system_clock::to_time_t(now);
string timeStr = ctime(&time);
timeStr.pop_back(); // 去除换行符
return timeStr;
}
// ==================== 9. 随机数生成 ====================
// 生成指定范围内的随机整数
int randomInt(int min, int max) {
static random_device rd;
static mt19937 gen(rd());
uniform_int_distribution<> dist(min, max);
return dist(gen);
}
// 生成随机字符串
string randomString(int length) {
static const string chars =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string result;
for (int i = 0; i < length; i++) {
result += chars[randomInt(0, chars.length() - 1)];
}
return result;
}
// ==================== 10. 内存管理函数 ====================
// 安全的数组创建和释放
template<typename T>
T* createArray(size_t size) {
return new T[size]();
}
template<typename T>
void safeDelete(T*& ptr) {
if (ptr != nullptr) {
delete ptr;
ptr = nullptr;
}
}
template<typename T>
void safeDeleteArray(T*& ptr) {
if (ptr != nullptr) {
delete[] ptr;
ptr = nullptr;
}
}
// ==================== 11. 额外实用函数 ====================
// 交换两个变量
template<typename T>
void mySwap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
// 计算数组长度
template<typename T, size_t N>
size_t arrayLength(T(&arr)[N]) {
return N;
}
// 判断是否为回文
bool isPalindrome(const string& str) {
string cleaned;
for (char c : str) {
if (isalnum(c)) {
cleaned += tolower(c);
}
}
string reversed = cleaned;
reverse(reversed.begin(), reversed.end());
return cleaned == reversed;
}
int main() {
// 一、基本变量类型
// 1. 整型
short sh=1000;
int n=100010;
long int l=100010;
long long ll=1000000010;
//2. 无符号整型
unsigned short gnedsh = 1000;
unsigned int gndn = 100010;
unsigned long gndl = 100010;
unsigned long long gndll = 1000000010;
unsigned char gndc=0;
//3. 字符类型
char c = 0;
wchar_t wc_t=0;//宽字符
char16_t ch16_t = 0;
char32_t ch32_t = 0;
char8_t ch8_t = 0;
//4. 浮点型
float fl=0.0;
double dou = 0.0;
long double ldou = 0.0;
//5. 布尔型
bool flag = true;
//6. 空类型
void x;
//7. 固定宽度整数类型(C++11, <cstdint>)
int8_t n8_t = 1000;
int16_t n16_t = 10000000000000010;
int32_t n32_t = 1000000000000000000000010;
int64_t n64_t = 100000000000000000000000000000000000000000000000010;
intptr_t np_t = 1000000000010;
size_t s_t = 1000000000010;
ptrdiff_t ptrd_dif_f_t = 1000000000010;
intmax_t n_MAX_t = 1000000000000000000000000000000000000000000000000000000000000000010;
//数组类型
//1. 内置数组(C风格数组)
//一维数组:
const long long = 99999;
long long a[1000000010];
long long A[N];
long long wet[10] = { 1,2,3,4,5,6,7,8,9,10 };
//====================分割线===============================//
//多维数组:
int two[100010][100010];
int three[100010][100010][100010]
//字符数组:
char ch_one[100010];
char hellow[5] = "你好!!!";
//指针数组
int* ptrArr[10]{1,2,3,4,5,6,7,8,9,10};
// 数组指针
int(*arrPtr)[5]=nullptr;
// 数组引用
int(&arrRef)[5]= nullptr;
//动态数组
int* pty = new w[100010];
//类型修饰符
const NM=1e9;
volatile i=0;
mutable soler;
constexpr MA_XN{};
//类型别名
typedef str string;
using LL = long long;
return 0;
}
全部评论 2
一赞拿走



18小时前 来自 湖北
2为了罐头,点赞+评论
13小时前 来自 安徽
0























有帮助,赞一个