boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

C++如何使用STL容器adaptors实现适配器模式


avatar
作者 2025年9月4日 10

STL容器适配器通过封装底层容器提供受限接口,体现适配器模式思想:std::stack、std::queue、std::priority_queue基于deque等容器实现特定行为;可自定义适配器如StackAdapter封装OldBuffer提供标准接口,或EvenQueue扩展std::queue实现偶数过滤,展示接口转换与行为定制。

C++如何使用STL容器adaptors实现适配器模式

STL中的容器适配器(container adaptors)并不是设计模式中“适配器模式”的直接实现,但它们在思想上有相似之处:通过封装已有组件,提供新的接口。C++标准库中的

stack

queue

priority_queue

就是典型的容器适配器,它们基于底层容器(如

deque

vector

list

)进行封装,限制或调整接口,以满足特定数据结构的行为需求。

理解STL容器适配器的工作方式

STL容器适配器不提供遍历功能,也不暴露底层容器的全部接口,只提供一组受限的操作。这种“接口转换”正是适配器思想的核心。

例如:

  • std::stack

    适配任意支持

    push_back

    pop_back

    的容器(如

    vector

    deque

    ),提供后进先出(LIFO)语义。

  • std::queue

    使用双端队列(

    deque

    默认)实现先进先出(FIFO)。

  • std::priority_queue

    将底层容器构造成结构,实现按优先级出队。

它们通过模板参数接受底层容器类型,实现灵活适配:

立即学习C++免费学习笔记(深入)”;

 std::stack<int, std::vector<int>> s;  // 使用 vector 作为底层容器 std::queue<int, std::list<int>> q;    // 使用 list std::priority_queue<int> pq;           // 默认使用 vector 

模拟适配器模式:封装旧接口,提供新行为

虽然STL容器适配器本身不是设计模式的完整实现,但我们可以借鉴其方式,实现符合“适配器模式”意图的类。

假设有一个旧的容器类

OldBuffer

,它提供

add

get_last

方法,但我们希望将其适配为一个标准的栈接口。

 class OldBuffer { public:     void add(int x) { data.push_back(x); }     int get_last() {          if (data.empty()) throw std::runtime_error("empty");         int val = data.back();         data.pop_back();         return val;     }     bool empty() const { return data.empty(); } private:     std::vector<int> data; }; 

现在我们创建一个适配器,使其接口符合

std::stack

风格:

 template <typename T> class StackAdapter { private:     OldBuffer buffer;  // 被适配的对象 public:     void push(const T& item) { buffer.add(item); }     void pop() {          if (!empty()) buffer.get_last();      }     T top() {          // 这里需要技巧:OldBuffer 没有 peek,只能取后模拟         T val = buffer.get_last();         buffer.add(val);         return val;     }     bool empty() const { return buffer.empty(); } }; 

这个

StackAdapter

就是一个典型的对象适配器:它封装了旧类,提供标准栈的

push

pop

top

接口,使旧代码能无缝集成到新系统中。

结合STL适配器机制定制行为

你也可以扩展STL适配器的思想,创建自己的适配器。例如,定义一个只允许插入偶数的队列:

 template <typename T = int, typename Container = std::deque<T>> class EvenQueue { private:     std::queue<T, Container> q; public:     void push(const T& value) {         if (value % 2 == 0) {             q.push(value);         }         // 忽略奇数     }     void pop() { q.pop(); }     T front() const { return q.front(); }     bool empty() const { return q.empty(); }     size_t size() const { return q.size(); } }; 

这个类复用了

std::queue

的行为,但通过重写

push

实现了过滤逻辑,体现了适配器对行为的“转换”作用。

基本上就这些。STL容器适配器虽不是goF适配器模式的典型示例,但其封装、接口转换的思想完全一致。通过继承或组合已有容器,你可以轻松构建符合特定需求的新接口,这正是适配器价值所在。



评论(已关闭)

评论已关闭