适配器
适配器(adaptor)是STL的一个通用概念,容器、迭代器和函数都有适配器。
本质上,一个适配器是一种机制,能使某种事物的行为看起来像另一种事物一样。一个容器适配器能接受一种已有的容器,使其看起来像一种不同的类型。
1.每个容器适配器都基于底层容器类型的操作定义了自己的特殊操作,我们只可以使用适配器操作,而不能使用底层容器类型的操作。
容器适配器的应用举例
2.迭代器适配器
插入器是一种迭代器适配器,它接受一个容器,生成一个迭代器,能实现向给定容器添加元素。
- 插入迭代器又称插入器,本质上是一种迭代器的适配器。标准库算法为了保证通用性,并不直接操作容器,而是通过迭代器来访问容器元素。因此,算法不具备向容器插入元素的能力。而插入器正是帮助算法实现向容器插入元素的机制。
顺序容器适配器——stack
Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.
stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the “back” of the specific container, which is known as the top of the stack.
就是说:栈被实现为容器适配器,它是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素从特定容器的“后面”(即栈顶)被加入/弹出。
The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:
- empty
- size
- back
- push_back
- pop_back
stack栈的实现
栈默认基于deque实现,也可以在list或vector之上实现。
注意:每个容器适配器都基于底层容器类型的操作定义了自己的特殊操作,我们只可以使用适配器的操作,而不能使用底层容器类型的操作。