STL 5 适配器
STL 适配器是一类特殊的组件,用于修改其他组件的接口,使其适配特定场景。它们本身不提供完整功能,而是通过包装现有组件来改变其行为。
文章目录
- 1.适配器
- 1.三种主要容器适配器
- 1.原理
- 2.std::stack
- 3.std::queue
- 4.std::priority_queue
- 2.常见迭代器适配器
- 3.函数适配器
- 1.std::bind
- 2.std::function
1.适配器
适配器是一种结构型设计模式,通过改变现有组件的接口,使其符合客户端的需求。在 STL 中,适配器主要分为三类:
1.容器适配器(Container Adapters)
2.迭代器适配器(Iterator Adapters)
3.函数适配器(Function Adapters)
1.三种主要容器适配器
1.原理
适配器内部持有一个被适配对象的实例,并通过转发调用其方法来实现新接口
2.std::stack
LIFO(后进先出)栈结构
std::stack默认使用std::deque作为底层容器,也可指定其他容器(需支持back()、push_back()、pop_back())
3.std::queue
FIFO(先进先出)队列结构
std::queue默认使用std::deque作为底层容器,也可指定其他容器(需支持front()、back()、push_back()、pop_front())
4.std::priority_queue
优先级队列(最大堆)
通常使用堆(如二叉堆)实现,保证插入和删除操作的时间复杂度为 O (log n)。
2.常见迭代器适配器
1.std::reverse_iterator 反向遍历容器
std::rbegin(v), std::rend(v)
2.std::back_insert_iterator 在容器尾部插入元素 std::back_inserter(v)
3.std::front_insert_iterator 在容器头部插入元素 std::front_inserter(l)
4.std::insert_iterator 在指定位置插入元素 std::inserter(v, pos)
5.std::move_iterator 将普通迭代器转换为移动迭代器 std::make_move_iterator(it)
3.函数适配器
1.std::bind
通用参数绑定和重排 bind(func, _1, 2)
template< class F, class… Args >/unspecified/ bind( F&& f, Args&&… args );
1.f:要绑定的可调用对象(函数、成员函数、函数对象等)。
2.args:要绑定的参数列表,可包含占位符(如 std::placeholders::_1)。
3.占位符(Placeholders)
std::placeholders::_1, _2, _3, … 表示新函数的第 1、2、3… 个参数:
2.std::function
std::function 是 C++11 引入的一种通用多态函数包装器,它可以存储、复制和调用任何可调用对象(函数、Lambda、函数指针、成员函数等)。
1.核心功能
1.类型擦除:将不同类型的可调用对象包装为统一接口。
2.多态存储:可以存储函数、Lambda、函数对象等。
3.延迟调用:存储可调用对象,在需要时执行。
std::function<int(int, int)> add
2.性能开销
1.类型擦除:运行时需动态查找调用目标,比直接调用慢约 20%。
2.堆分配:当存储的对象较大时,可能触发堆分配。
3.优化建议
1.优先使用 Lambda:直接传递 Lambda 而非 std::function,避免类型擦除。
2.小对象优先值传递:通过 std::function 存储小对象(如简单 Lambda)。
3.大对象使用引用:存储大对象时使用 std::function<void()> 和捕获列表。