常用的20个c++函数
本文总结了20个实用C++函数示例,涵盖字符串处理、文件操作、随机数生成、时间测量等常见需求。所有代码均采用现代C++17/20标准,可直接编译运行。亮点包括:字符串分割与修剪函数、文件存在性检查、随机数生成器、大小写转换、毫秒级时间戳获取、RAII计时器、线程安全单例模板等。每个函数都附带功能说明和关键注释,适合工程开发直接使用或面试参考。这些代码体现了现代C++的最佳实践,如移动语义、类型安全
·
下面给出 20 个在工程中最常见、面试最常问、日常开发最实用的 C++ 函数示例。
每个函数都遵循现代 C++(C++17/20)风格,包含:
• 简短功能说明
• 完整可编译代码(单文件即可运行)
• 关键要点注释
• 复杂度与注意事项
直接复制即可编译运行(g++ -std=c++17 xxx.cpp)。
- 安全的字符串分割
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> split(const std::string& s,
char delim = ' ',
bool skip_empty = true)
{
std::vector<std::string> res;
std::stringstream ss(s);
for (std::string item; std::getline(ss, item, delim); )
if (!skip_empty || !item.empty())
res.push_back(std::move(item));
return res;
}
- 去掉首尾空白字符
#include <string>
#include <cctype>
std::string trim(std::string s)
{
auto not_space = [](int ch){ return !std::isspace(ch); };
s.erase(s.begin(), std::find_if(s.begin(), s.end(), not_space));
s.erase(std::find_if(s.rbegin(), s.rend(), not_space).base(), s.end());
return s;
}
- 判断文件是否存在
#include <filesystem>
bool file_exists(const std::string& path) {
return std::filesystem::exists(path) &&
std::filesystem::is_regular_file(path);
}
- 读取整个文本文件
#include <fstream>
#include <string>
std::string read_file(const std::string& path)
{
std::ifstream ifs(path, std::ios::in | std::ios::binary);
if (!ifs) throw std::runtime_error("cannot open " + path);
return std::string(std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>());
}
- 快速生成随机整数 [a,b]
#include <random>
int rand_int(int a, int b)
{
static thread_local std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<int> dist(a, b);
return dist(rng);
}
- 判断字符串是否为数字
#include <cctype>
bool is_number(const std::string& s)
{
return !s.empty() &&
std::all_of(s.begin(), s.end(), [](unsigned char c){ return std::isdigit(c); });
}
- 大写/小写转换
#include <algorithm>
#include <cctype>
inline std::string to_upper(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c){ return std::toupper(c); });
return s;
}
inline std::string to_lower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c){ return std::tolower(c); });
return s;
}
- 获取当前时间戳(毫秒)
#include <chrono>
int64_t now_ms()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
- 计时器(RAII)
#include <chrono>
#include <iostream>
class Timer {
public:
Timer(const char* name = "") : name_(name), start_(std::chrono::high_resolution_clock::now()) {}
~Timer() {
auto us = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now() - start_).count();
std::cout << name_ << " cost: " << us << " us\n";
}
private:
const char* name_;
std::chrono::high_resolution_clock::time_point start_;
};
- 单例模板(懒汉 + 局部静态,线程安全)
template<typename T>
class Singleton {
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static T& instance() {
static T inst;
return inst;
}
protected:
Singleton() = default;
~Singleton() = default;
};
- 范围 for 支持枚举类
#include <type_traits>
template<typename E>
struct EnableBitMask { static constexpr bool enable = false; };
template<typename E>
constexpr std::enable_if_t<EnableBitMask<E>::enable, E>
operator|(E a, E b) { return static_cast<E>(static_cast<std::underlying_type_t<E>>(a) |
static_cast<std::underlying_type_t<E>>(b)); }
// 用法:特化 EnableBitMask<MyEnum>::enable = true;
- 安全的字节序转换(32 位)
#include <cstdint>
#include <cstring>
inline uint32_t swap32(uint32_t x)
{
#if defined(__GNUC__) || defined(__clang__)
return __builtin_bswap32(x);
#else
return ((x & 0xFF000000) >> 24) |
((x & 0x00FF0000) >> 8) |
((x & 0x0000FF00) << 8) |
((x & 0x000000FF) << 24);
#endif
}
- 打印容器内容(通用)
#include <iostream>
#include <iterator>
template<typename Container>
void print(const Container& c, const char* sep = " ")
{
std::copy(c.begin(), c.end(),
std::ostream_iterator<typename Container::value_type>(std::cout, sep));
std::cout << '\n';
}
- 计算数组/容器元素和
#include <numeric>
template<typename Container>
auto sum(const Container& c)
{
using value_type = typename Container::value_type;
return std::accumulate(c.begin(), c.end(), value_type{});
}
- 快速排序(vector 版)
#include <vector>
void quick_sort(std::vector<int>& v, int l, int r)
{
if (l >= r) return;
int pivot = v[l + (r - l) / 2];
int i = l, j = r;
while (i <= j) {
while (v[i] < pivot) ++i;
while (v[j] > pivot) --j;
if (i <= j) std::swap(v[i++], v[j--]);
}
if (l < j) quick_sort(v, l, j);
if (i < r) quick_sort(v, i, r);
}
- 二分查找(返回迭代器)
template<typename RandomIt, typename T>
RandomIt binary_find(RandomIt first, RandomIt last, const T& value)
{
auto it = std::lower_bound(first, last, value);
return (it != last && *it == value) ? it : last;
}
- 计算 SHA256(OpenSSL 封装)
#include <openssl/sha.h>
#include <iomanip>
#include <sstream>
std::string sha256(const std::string& str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const unsigned char*>(str.data()), str.size(), hash);
std::ostringstream oss;
for (unsigned char c : hash)
oss << std::hex << std::setw(2) << std::setfill('0') << +c;
return oss.str();
}
- 获取可执行文件所在目录
#include <filesystem>
std::string exe_dir()
{
return std::filesystem::canonical("/proc/self/exe").parent_path().string();
}
- 简单的日志宏(线程安全)
#include <iostream>
#include <mutex>
#define LOG(level) \
LogHelper(__FILE__, __LINE__, #level).stream()
class LogHelper {
public:
LogHelper(const char* file, int line, const char* level)
{
std::lock_guard<std::mutex> lk(mtx_);
stream_ << "[" << level << "] " << file << ':' << line << " ";
}
~LogHelper() { std::lock_guard<std::mutex> lk(mtx_); std::cerr << stream_.str() << '\n'; }
std::ostream& stream() { return stream_; }
private:
static std::mutex mtx_;
std::ostringstream stream_;
};
std::mutex LogHelper::mtx_;
- 命令行解析(极简)
#include <unordered_map>
#include <string>
class ArgParser {
public:
ArgParser(int argc, char* argv[])
{
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg.find("--") == 0) {
auto pos = arg.find('=');
if (pos != std::string::npos)
data_[arg.substr(2, pos - 2)] = arg.substr(pos + 1);
else
data_[arg.substr(2)] = "";
}
}
}
bool has(const std::string& key) const { return data_.count(key); }
std::string get(const std::string& key, const std::string& def = "") const {
auto it = data_.find(key);
return it == data_.end() ? def : it->second;
}
private:
std::unordered_map<std::string, std::string> data_;
};
使用示例
int main()
{
// 1. 分割字符串
auto v = split("a,b,,c", ',');
print(v, "|"); // a|b|c|
// 2. 计时
{
Timer t("sleep");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// 3. 随机数
std::cout << rand_int(1, 100) << '\n';
// 4. 日志
LOG(INFO) << "hello world";
}
以上 20 个函数覆盖了字符串处理、文件 IO、时间、随机、算法、并发、系统路径、日志、命令行等日常开发 80% 的场景,可直接放入公共头文件或工具库中复用。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)