You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中实现自定义栈迭代器?相关代码问题咨询

解决C++自定义栈迭代器的实现问题

原代码的问题分析

你的代码存在几个关键问题导致无法正确实现迭代器:

  • 继承std::stack时未指定模板参数,应显式声明为std::stack<T, container>,否则基类模板未特化会引发编译错误。
  • 迭代器的typedef错误:硬编码使用std::deque::iterator,但类允许自定义容器类型(container模板参数),需基于传入的container类型定义迭代器。
  • 缺少begin()和end()成员函数的具体实现,这两个是暴露迭代器的核心接口。

修正后的完整代码

#include <iostream>
#include <stack>
#include <deque>
#include <iterator>

template <typename T, class container = std::deque<T>>
class MutantStack : public std::stack<T, container>
{
public:
    // 默认生成构造、析构、拷贝构造和赋值运算符
    MutantStack() = default;
    ~MutantStack() = default;
    MutantStack(const MutantStack&) = default;
    MutantStack& operator=(const MutantStack&) = default;

    // 基于底层容器定义迭代器类型
    typedef typename container::iterator iterator;
    typedef typename container::const_iterator const_iterator;
    typedef typename container::reverse_iterator reverse_iterator;
    typedef typename container::const_reverse_iterator const_reverse_iterator;

    // 普通迭代器接口
    iterator begin() { return this->c.begin(); }
    const_iterator begin() const { return this->c.begin(); }

    iterator end() { return this->c.end(); }
    const_iterator end() const { return this->c.end(); }

    // 反向迭代器接口(可选)
    reverse_iterator rbegin() { return this->c.rbegin(); }
    const_reverse_iterator rbegin() const { return this->c.rbegin(); }

    reverse_iterator rend() { return this->c.rend(); }
    const_reverse_iterator rend() const { return this->c.rend(); }
};

// 测试示例
int main() {
    MutantStack<int> mstack;
    mstack.push(5);
    mstack.push(17);

    std::cout << "Top element: " << mstack.top() << std::endl;

    // 使用迭代器遍历栈元素
    std::cout << "Iterating stack elements: ";
    for (MutantStack<int>::iterator it = mstack.begin(); it != mstack.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

关于this->c.begin()的含义

std::stack是容器适配器,本身不存储元素,依赖底层容器(默认是std::deque)管理数据。c是std::stack中定义的保护成员变量,直接指向这个底层容器。

this->c.begin()就是调用底层容器的begin()方法,返回该容器的起始迭代器。通过这种方式,我们可以复用底层容器的迭代器实现,无需自行编写迭代器逻辑。

需要注意:c是保护成员,只有继承std::stack的子类才能直接访问它。

内容的提问来源于stack exchange,提问作者ASALEK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:15:45