C++编程语言日常20个高级经典用法(含完整源码与输出)

yumo6662个月前 (09-13)技术文章24


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!

相关文章

C++语言程序员编程必收藏的20个经典实战案例(附完整源码)

C++ 作为一门底层高性能语言,拥有广泛的应用领域,从系统开发、游戏引擎、图形图像、嵌入式到人工智能等,都能看到它的身影。本文为你整理并实操了 20 个 必收藏的经典 C++ 案例,帮助你提升实战水平...

C 语言编程_c语言编程题经典100例及答案

小学阶段的 C 语言编程以入门级语法和生活化场景为主,涉及的数学知识均是小学生已学或易理解的内容,核心是将数学概念与基础编程逻辑(变量、运算、判断、循环)结合,解决简单实际问题。以下按「数学知识类别」...

单片机C语言编程,心得都在这里了

单片机写代码总踩坑,头文件被无视,老工程师的经验哪里来?前几天写8x8矩阵键盘的程序,搞了三天代码一直乱报错。后来发现自己连头文件是什么都不清楚,之前写的都是小程序,压根没碰过.h文件。看别人的程序都...

C语言入门:二重循环_c语言的双重循环

什么是二重循环?循环体内可以是任何语句,任何语句,当然就可以是另一个循环语句。二重循环,就是循环里面再套一个循环。就像我们日常生活中,一周有7天(外层循环),每天有24小时(内层循环),这样组合起来就...

C 语言语法最小完备集详细文档_c语言中最小怎么表示

1. 概念定义与理论基础1.1 最小完备集的定义C 语言语法最小完备集是指能够实现所有可计算函数(满足图灵完备性)的最小语法子集。这一子集仅包含不可被其他语法元素等价替代的核心成分,剔除所有冗余语法结...