C++ 标准库概述

C++ 标准库概述

C++ 标准库(Standard Library)是一组核心功能模块的集合,包含容器、算法、迭代器、字符串处理、输入/输出等功能。它基于模板实现,与 C++ 语言紧密集成,是开发高效、可移植程序的基础工具。


主要组成部分

标准模板库(STL)

STL 提供以下核心组件:

  • 容器 :如 vectorlistmapunordered_set,用于数据存储。
  • 算法 :如 sortfindtransform,作用于容器或迭代器范围。
  • 迭代器 :如 begin()end(),提供对容器的统一访问接口。
字符串处理

std::stringstd::wstring 类支持动态字符串操作,包括拼接、查找、替换等。

输入/输出(I/O)
  • <iostream>:提供 cincoutcerr 等标准流。
  • <fstream>:支持文件读写(ifstreamofstream)。
智能指针

std::unique_ptrstd::shared_ptr 等用于自动化资源管理,避免内存泄漏。

多线程支持(C++11 起)

<thread><mutex><atomic> 等库支持并发编程。


常用代码示例

容器与算法
cpp 复制代码
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> nums = {3, 1, 4, 1, 5};
    std::sort(nums.begin(), nums.end()); // 排序
    for (int num : nums) {
        std::cout << num << " ";
    }
    return 0;
}
字符串操作
cpp 复制代码
#include <string>
#include <iostream>

int main() {
    std::string str = "Hello";
    str += " C++";
    std::cout << str.substr(0, 5); // 输出 "Hello"
    return 0;
}
文件读写
cpp 复制代码
#include <fstream>
#include <string>

int main() {
    std::ofstream file("example.txt");
    file << "Writing to a file.\n";
    file.close();
    return 0;
}

版本演进

  • C++98/03:初始标准,包含 STL 基础功能。
  • C++11:引入智能指针、多线程库、移动语义等。
  • C++17 :新增 std::optionalstd::filesystem 等。
  • C++20:加入范围(Ranges)、协程(Coroutines)等特性。

学习资源

  • 官方文档cppreference.com
  • 书籍:《The C++ Standard Library》(Nicolai M. Josuttis)
  • 实践:通过项目或在线编程平台(如 LeetCode)练习标准库的使用。
相关推荐
FAFU_kyp2 小时前
Rust 所有权(Ownership)学习
开发语言·学习·rust
superman超哥2 小时前
Rust 异步性能的黑盒与透视:Tokio 监控与调优实战
开发语言·后端·rust·编程语言·rust异步性能·rust黑盒与透视·tokio监控与调优
lkbhua莱克瓦242 小时前
进阶-存储对象2-存储过程上
java·开发语言·数据库·sql·mysql
Mr -老鬼2 小时前
Rust 知识图谱 -进阶部分
开发语言·后端·rust
LawrenceLan2 小时前
Flutter 零基础入门(十三):late 关键字与延迟初始化
开发语言·前端·flutter·dart
深耕AI2 小时前
【wordpress系列教程】03 网站页面的编辑
开发语言·前端
恒者走天下2 小时前
c++ cpp项目面经分享
c++
烟锁池塘柳02 小时前
C++程序脱离环境运行:详解OpenCV动态库依赖部署 (Deployment)
c++·opencv·webpack