注册 登录
编程论坛 VC++/MFC

答案是这么写的,不能编译,不知道怎么改

不懂CCC 发布于 2015-05-20 12:56, 2139 次点击
#include <string>
#include <iostream>
#include <vector>

using namespace std;

typedef string elemtype;
class stack{
    public:
        virtual ~stack(){}
        virtual bool pop (elemtype& )=0;
        virtual bool push(const elemtype& )=0;
        virtual bool peek(int index,elemtype&)=0;
        
};

ostream& operator<<(ostream &os,const stack &rhs)
  {rhs.print();return os;}
   
class lifo_stack : public stack
{
    public:
        lifo_stack (int capacity=0):_top(0)
        {if(capacity) _stack.reserve(capacity);}
        int size() const{return _stack.size();}
        bool empty() const {return ! _top;}
        bool full() const {return size() >= _stack.max_size();}
        int top() const (return _top;)
        void print (ostream &os=cout) const;
        
        bool pop(elemtype &elem);
        bool push(const elemtype &elem);
        bool peek(int,elemtype&){return false;}
    private:
        vector<elemtype>_stack;
        int _top;
    };
   
    bool lifo_stack::pop(elemtype &elem){
        if (empty() ) return false;
        elem=_stack[--_top];
        _stack.pop_back();
        return true;
}
    bool lifo_stack::push(const elemtype &elem){
    if(full()) return false;
    _stack.push_back(elem);
    ++_top;
    return ture;
    }
    void lifo_stack::print(ostream &os) const{
      vector<elemtype>::const_reverse_iterator
            rit=_stack.rbegin(),
            rend=_stack.rend();
            
      os<<endl;
    }
   
    bool peekback_stack::
    peek (int index,elemtype &elem)
    {
        if(empty())
           return false;
        if (index<0|| index>=size())
         return false;
         elem=_stack[index];
         return true;
    }
    void peek(stack &st,int index)
    {
        cout <<endl;
        string t;
        if (st.peek(index,t))
           cout<<"peek:"<<t;
        else cout<<"peek failed!";
        cout <<endl;
    }
   
int main()
{
    lifo_stack st;
    string str;
    while (cin>>str &&!st.full())
           st.push(str);
           cout<<'\n'<<"about to call peek () whith lifo_stack"<<endl;
           peek(st,st.top()-1);
           cout<<st;
           
           peekback_stack pst;
           
           while (!st.empty()){
               string t;
               if (st.pop(t))
                 pst.push(t);
           }
    cout<<"about to call peek () with peekback_stack"<<endl;
    peek(pst,pst.top()-1);
    cout<<pst;
}
1 回复
#2
yuccn2015-05-20 22:21
提示什么错误?

目测 main 内少了个return
1