【问题标题】:Add more features to stack container为堆栈容器添加更多功能
【发布时间】:2015-06-22 07:56:34
【问题描述】:

我正在使用 STL 堆栈容器的默认功能(推送、弹出、顶部、空、大小)。如果我想添加更多功能,例如从堆栈中间访问元素。

我该怎么做?

谢谢

【问题讨论】:

  • 你没有。那不是堆栈。如果您想要更强大的容器,请使用不同的容器。喜欢std::vector。
  • 有人可能选择使用堆栈的原因之一是它意味着需要一组特定的操作,从而为代码读者提供一些可能使用的算法的提示。它还意味着能够切换到堆栈的另一个实现(例如,查看它是否性能更好或使用更少的内存)。如果您有某种超出预期界面的“电源堆栈”,那么您已经使这些含义无效,并且会使代码的审阅者/维护者感到困惑。
  • stack 默认使用双端队列来实现,但只提供了 5 个功能。我可以为堆栈制作一个通用容器吗?
  • 知道std::deque 是std::stack 的底层,为什么不直接使用std::deque?

标签: c++ visual-c++ stl


【解决方案1】:

如果这是面试问题之类的,无论如何你都必须这样做,你可以像下面的代码那样做。派生自std::stac,重载operator[]

#include <iostream>
#include <algorithm>
#include <stack>
#include <exception>
#include <stdexcept>

template <typename T>
class myStack:public std::stack<T>
{
    public:
        T operator[](long index)
        {
            std::stack<T> temp;
            T tempVal;
            for(long i=0;i<index;++i)
            {
                if(this->template empty())
                    throw std::out_of_range("Index out of range");
                tempVal = this->template  top();
                temp.push(tempVal);
                this->template pop();
            }

            //T retVal = this->template top();
            while(!temp.empty())
            {
                T tempVal = temp.top();
                this->template push(tempVal);
                temp.pop();
            }

            return tempVal;
        }
};

int main(void)
{
    myStack<int> st;

    st.push(5);
    st.push(1);
    st.push(7);
    st.push(9);
    st.push(4);

    std::cout<<"3rd Element :"<<st[3]<<std::endl;
    return 0;
}

【讨论】:

  • 如果不是面试题呢?
  • 如果它用于现实世界的问题,我建议不要使用堆栈进行随机访问或其他东西,而是使用向量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 2016-12-14
  • 2021-06-15
  • 1970-01-01
  • 2013-11-28
  • 2015-05-11
  • 2019-10-16
相关资源
最近更新 更多