2
#include <iostream>
#include <vector>

typedef std::vector<int> vector_int;
//My pop exception class!
class cPopOnEnpty{};
//My push exception class!
class cPushOnFull{};

class cStack
{
private:
    vector_int v;
    int m_top, m_cap;
public:
    cStack(int capacity):m_top(0),m_cap(capacity){}
    void pop()
    {
        if(m_top==0)
            throw cPopOnEnpty();
        v.erase(v.begin()+m_top);
        m_top--;
    }
    void push(int const& i)
    {
        if(m_top==m_cap)
            throw cPushOnFull();
        v.push_back(i); m_top++;
    }
};

int main(int argc, char **argv)
{
    cStack c(3);
    try {
        c.pop(); //m_top = 0 So exception should be thrown!
        c.push(2); //m_top = 1
        c.push(10); //m_top =2
        c.push(3);  //m_top =3
        c.push(19); //m_top = 4 Exception should be thrown here!
    }
    catch (cPopOnEnpty&)
    {
        std::cerr<< "Caught: Stack empty!"<<std::endl;
    }
    catch(cPushOnFull&)
    {
        std::cerr<<"Caught: Stack full!"<<std::endl;
    }
    return 0;
}

O/P - 捕获:堆栈为空!

所需的 O/P - 捕获:堆栈为空!抓到:堆满了!

在上面的代码中,我正在处理空向量上的弹出和满(容量受我限制)向量的推送。在这些情况下,当控件到达 main 末尾并且程序退出时,我没有得到我想要的 o/p。我怎样才能使这个恢复,以便在处理一个呼叫的异常后转到下一个呼叫?

c.pop()这里应该执行下一个语句。需要帮忙!

4

3 回答 3

2

为每个方法调用编写一个 Try/Catch 块。

try
{
    c.pop(); //m_top = 0 So exception should be thrown!
}
catch(cPopOnEnpty&)
{
    std::cerr<< "Caught: Stack empty!"<<std::endl;
}
于 2013-02-20T18:22:11.193 回答
0

C++ 不允许在异常后恢复,因为堆栈已经被展开(不像 Lisp 的条件是完全不同的野兽)。

您将不得不以其他方式构建您的代码,例如@RobertHarvey 建议的那样。

于 2013-02-20T18:27:44.703 回答
0
try {
        c.pop(); //m_top = 0 So exception should be thrown!
    }
    catch (cPopOnEnpty&)
        {
            std::cerr<< "Caught: Stack empty!"<<std::endl;
        }
    try{
        c.push(2); //m_top = 1
        c.push(10); //m_top =2
        c.push(3);  //m_top =3
        c.push(19); //m_top = 4 Exception should be thrown here!
    }
    catch(cPushOnFull&)
    {
        std::cerr<<"Caught: Stack full!"<<std::endl;
    }

问题解决了!谢谢你们!:D

于 2013-02-20T18:40:06.163 回答