STL in C++ (Pre-Part)

The History of C++ STL

STL,全称标准模板库(Standard Template Library),是 C++ 中最为重要的部件之一,也是 C++ 如此强大的一大因素。STL 的架构思想主要由 Alexander Stepanov 所创建,他也是最早提出泛型编程概念的人之一。

C++ STL 最早由 Alexander Stepanov 在 1992 年向 ANSI/ISO C++ 标准委员会提交,并在 1994 年被正式采纳,最终在 C++98 标准中成为 C++ 标准库的一部分。自此,STL 经过多次改进和扩展,并在 C++11 和后续版本中增加了更多功能和优化(移动语义等)。

Algorithms, Containers, Functions and Iterators

STL 提供了四大部件:算法、容器、函数和迭代器。并且这四大部件彼此分离,使得 STL 的可扩展性非常好,你可以实现自己的容器或迭代器等来匹配标准模板库中的其他部件。

STL 容器包括泛型的序列容器和关联容器。容器是存储数据的对象,通过模板,你可以用 STL 容器存储任何内置类型或是用户自定义类型。常见的容器有:

  • std::array
  • std::vector
  • std::deque: A double-ended queue providing fast insertion and deletion at both ends.
  • std::list: A doubly circular linked list that allows bidirectional traversal.
  • std::forward_list :A singly forward linked list that supports only forward traversal.
  • std::set: An ordered container that stores unique elements and uses a balanced binary search tree.
  • std::map: An ordered container that stores key-value pairs with unique keys, using a balanced binary search tree.
  • std::unordered_map
  • std::unordered_set

迭代器是 STL 中访问容器的方式。迭代器是对裸指针的封装,相当于指向当前位置的指针。与裸指针相比,迭代器通常包含边界检查(bound checking)、统一性和可扩展性。不同的迭代器还会提供不同访问容器的语义。在 STL 中,我们有五种类型的迭代器:

  • 输入迭代器:只能读
  • 输出迭代器:只能写
  • 前向迭代器:可读可写,向前移动
  • 双向迭代器:可读可写,双向移动
  • 随机访问迭代器

算法提供了对容器进行操作的方法。这些算法是通用的,可以与任何容器和迭代器配合使用。常见的算法有:

  • std::sort
  • std::find
  • std::accumulate
  • std::copy
  • std::transform
  • std::for_each

函数对象是可以像函数一样使用的对象。它们通常用于算法中来提供灵活的操作。常见的函数对象有:

  • std::less
  • std::greater
  • std::plus
  • std::minus