网站首页 > 技术文章 正文
C++ 是一门强大而灵活的编程语言,擅长系统开发、高性能计算、游戏开发等多个领域。以下是 20 个高频但极具价值的 C++ 高级用法案例,配套完整代码与输出结果,助力你快速掌握进阶技巧。
01. 使用
std::optional
优雅处理函数返回值
#include <iostream>
#include <optional>
std::optional<int> divide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
int main() {
auto result = divide(10, 2);
if (result) std::cout << "Result: " << *result << std::endl;
else std::cout << "Division by zero!" << std::endl;
}
输出:
Result: 5
02. 使用
std::variant
表示多种可能的数据类型
#include <iostream>
#include <variant>
int main() {
std::variant<int, std::string> data;
data = 42;
std::cout << "int: " << std::get<int>(data) << std::endl;
data = "Hello";
std::cout << "string: " << std::get<std::string>(data) << std::endl;
}
输出:
int: 42
string: Hello
03. 使用
std::any
存储任意类型
#include <iostream>
#include <any>
int main() {
std::any val = 5;
std::cout << "Value: " << std::any_cast<int>(val) << std::endl;
val = std::string("C++");
std::cout << "Value: " << std::any_cast<std::string>(val) << std::endl;
}
输出:
Value: 5
Value: C++
04. 使用
std::function
实现高阶函数
#include <iostream>
#include <functional>
void execute(std::function<void()> func) {
func();
}
int main() {
execute([] { std::cout << "Hello Lambda" << std::endl; });
}
输出:
Hello Lambda
05. 使用
constexpr
优化编译期计算
#include <iostream>
constexpr int factorial(int n) {
return (n <= 1) ? 1 : (n * factorial(n - 1));
}
int main() {
constexpr int result = factorial(5);
std::cout << "Factorial: " << result << std::endl;
}
输出:
Factorial: 120
06. 使用结构化绑定简化变量拆解
#include <iostream>
#include <tuple>
std::tuple<int, double> getData() {
return {10, 3.14};
}
int main() {
auto [a, b] = getData();
std::cout << "a: " << a << ", b: " << b << std::endl;
}
输出:
a: 10, b: 3.14
07. 使用范围 for 循环与
auto
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3};
for (auto& v : vec) {
std::cout << v << " ";
}
}
输出:
1 2 3
08. 使用
emplace_back
提升容器性能
#include <iostream>
#include <vector>
struct Person {
std::string name;
int age;
};
int main() {
std::vector<Person> people;
people.emplace_back("Alice", 30);
std::cout << people[0].name << " - " << people[0].age << std::endl;
}
输出:
Alice - 30
09. 使用
unique_ptr
实现智能指针管理
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(42);
std::cout << "Value: " << *ptr << std::endl;
}
输出:
Value: 42
10. 使用
shared_ptr
实现对象共享所有权
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> p1 = std::make_shared<int>(100);
std::shared_ptr<int> p2 = p1;
std::cout << "Shared value: " << *p2 << std::endl;
}
输出:
Shared value: 100
11. 使用 Lambda 捕获外部变量
#include <iostream>
int main() {
int x = 10;
auto print = [x]() { std::cout << "Captured x: " << x << std::endl; };
print();
}
输出:
Captured x: 10
12. 使用
decltype
自动获取类型
#include <iostream>
int main() {
int a = 5;
decltype(a) b = 10;
std::cout << "b: " << b << std::endl;
}
输出:
b: 10
13. 使用
typeid
获取运行时类型
#include <iostream>
#include <typeinfo>
int main() {
double d = 3.14;
std::cout << "Type: " << typeid(d).name() << std::endl;
}
输出(平台相关):
Type: d
14. 使用模板函数实现泛型编程
#include <iostream>
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << add(1, 2) << std::endl;
std::cout << add(1.5, 2.5) << std::endl;
}
输出:
3
4
15. 使用模板特化处理特殊类型
#include <iostream>
template <typename T>
void print(T val) {
std::cout << "Generic: " << val << std::endl;
}
template <>
void print(std::string val) {
std::cout << "String: " << val << std::endl;
}
int main() {
print(100);
print(std::string("C++"));
}
输出:
Generic: 100
String: C++
16. 使用
enum class
定义类型安全枚举
#include <iostream>
enum class Color { Red, Green, Blue };
int main() {
Color c = Color::Green;
if (c == Color::Green)
std::cout << "It's green!" << std::endl;
}
输出:
It's green!
17. 使用范围检查的
at()
方法
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
std::cout << v.at(1) << std::endl;
}
输出:
2
18. 使用
std::sort
对结构体排序
#include <iostream>
#include <vector>
#include <algorithm>
struct Student {
std::string name;
int score;
};
int main() {
std::vector<Student> list = {{"Tom", 80}, {"Alice", 90}};
std::sort(list.begin(), list.end(), [](auto& a, auto& b) {
return a.score > b.score;
});
for (auto& s : list)
std::cout << s.name << ": " << s.score << std::endl;
}
输出:
Alice: 90
Tom: 80
19. 使用
try-catch
实现异常处理
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("Something went wrong!");
} catch (const std::exception& e) {
std::cout << "Caught error: " << e.what() << std::endl;
}
}
输出:
Caught error: Something went wrong!
20. 使用文件流
fstream
读写文件
#include <iostream>
#include <fstream>
int main() {
std::ofstream out("test.txt");
out << "Hello, File!" << std::endl;
out.close();
std::ifstream in("test.txt");
std::string line;
std::getline(in, line);
std::cout << "Read: " << line << std::endl;
}
输出:
Read: Hello, File!
猜你喜欢
- 2025-09-21 C#串口组件的使用方法_c#串口控件使用方法
- 2025-09-21 Python 变量学习_python怎么用变量
- 2025-09-21 生产环境使用HBase,你必须知道的最佳实践 | 百万人学AI
- 2025-09-21 5年程序员总结—这几个C语言问题超纲了,小白勿进
- 2025-09-21 C 语言“翻译阶段”全解析:从字符到记号,编译器到底干了什么?
- 2025-09-21 【C语言·023】变长数组的栈分配机制与使用限制
- 2025-09-21 【C语言·006】字符常量与转义序列的编码对应关系
- 2025-09-21 剑指Offer:字符串转整数的实现与边界处理
- 2024-08-06 【PythonTip题库精编300题】第35题:十六进制转换为二进制
- 2024-08-06 学习编程第135天 python编程二、八、十、十六进制转换
- 最近发表
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)