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

STL中的容器适配器(container adaptors)并不是设计模式中“适配器模式”的直接实现,但它们在思想上有相似之处:通过封装已有组件,提供新的接口。C++标准库中的
stack
queue
priority_queue
deque
vector
list
STL容器适配器不提供遍历功能,也不暴露底层容器的全部接口,只提供一组受限的操作。这种“接口转换”正是适配器思想的核心。
例如:
std::stack
push_back
pop_back
vector
deque
std::queue
deque
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适配器的思想,创建自己的适配器。例如,定义一个只允许插入偶数的队列:
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适配器模式的典型示例,但其封装、接口转换的思想完全一致。通过继承或组合已有容器,你可以轻松构建符合特定需求的新接口,这正是适配器价值所在。
以上就是C++如何使用STL容器adaptors实现适配器模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号