【问题标题】:std::cout statements evaluation order [duplicate]std::cout 语句评估顺序 [重复]
【发布时间】:2015-04-07 22:12:54
【问题描述】:

pop() 函数有什么问题为什么不能正常工作?

class stack{
    int *p, *Cursor;
    int size ;
public:
    stack(int sz) {Cursor = p = new int[size=sz+1];} //consider the stack empty when its size is 1
    ~stack() {delete[] p;} //Cursor and P will be destroyed when the program finishes
    void push(int x) {Cursor+=1; *Cursor=x; size++;}
    int pop() {if(Cursor == p) return -1; int temp = *Cursor; Cursor--; size--; return (temp);}
    bool isEmpty(){return(Cursor == p);}
    bool isFull(){return(Cursor == p+size);}
};

这是我的测试:

stack A(3);
    std::cout<<"Empty: "<<A.isEmpty()<<std::endl;
    std::cout<<"Full: "<<A.isFull()<<std::endl;
    A.push(10);
    A.push(20);
    A.push(30);
    std::cout<<std::endl;
    std::cout<<" 1st pop: "<<A.pop()<<std::endl<<" 2nd pop: " <<A.pop()<<std::endl<<" 3rd pop: " <<A.pop()<<std::endl<<" 4th pop: " <<A.pop()<<std::endl;

我得到的输出是:

1st pop: -1
2nd pop: 10
3rd pop: 20
4th pop: 30

虽然我应该得到这样的东西:

1st pop: 30
2nd pop: 20
3rd pop: 10
4th pop: -1

问题是我哪里出错了?

【问题讨论】:

  • 分离弹出打印输出 (cout &lt;&lt; pop() &lt;&lt; endl; cout &lt;&lt; pop() &lt;&lt; ...)

标签: c++ stack


【解决方案1】:

没有出错,但是如果您将 pops 全部放在一个 std::cout 行中,则从右到左评估(在您的情况下)。一般来说。评估顺序未指定。有关这方面的更多详细信息,请参阅here

所以你正确地以插入的相反顺序获取元素,然后-1,然后将它们反向打印。

【讨论】:

【解决方案2】:

在代码的最后一行,您进行了几个函数调用(隐藏,但每个

【讨论】:

    猜你喜欢
    • 2011-12-04
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    相关资源
    最近更新 更多