本文介绍了std :: cout语句评估顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pop()函数怎么了,为什么它不能正常工作?
What is wrong with the pop() function why doesn't it work correctly?
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
问题是我在哪里出错了?
The question is where did I go wrong?
推荐答案
没什么大不了的,但是 pop
(如果您使用的话)从右到左进行评估(如果您将它们全部放入)一条 std :: cout
行.一般来说.未指定评估顺序.有关此详细信息,请参见此处.
Nothing did go wrong, but the pop
s get (in your case) evaluated from right to left if you put them all in one std::cout
line. In general. the evaluation order is unspecified. For more detail on this see here.
因此,您可以按相反的顺序正确获取元素,然后按 -1
顺序进行反转打印.
So you correctly get the elements in reverse order of insertion and then -1
and then print them reversed.
这篇关于std :: cout语句评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!