Phe*_*nom 2 c++ stack templates
这是我的功能,
template <class KeyType >
KeyType * Stack<KeyType>::Pop(KeyType& x) {
if (IsEmpty()) { //isempty is just a bool function
StackEmpty(); //just prints out that stack is empty
return 0; //bad coding breaking out of the function
}
x = stack[top--]; //stack is a pointer to an array, top is the top of the stack
return &x;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我不确定这将如何被称为主要.根据我的理解,pop函数不应该真正选择从堆栈弹出的内容.LIFO对吗?主要问题是Keytype&x参数究竟是什么以及如何在main中调用它?(在这种情况下,KeyType被初始化为KeyType*在此特定程序中堆叠一个int).
这是一个非常奇怪的设计功能.
Stack是由存储在堆栈中的类型(KeyType由于某种原因命名)参数化的类模板.该函数接受类型为reference 的输出参数 x,KeyType如果堆栈不为空,则将弹出的值赋给x.同时,它返回它的地址(它返回一个指针KeyType).如果在调用时堆栈为空pop(),它将调用StackEmpty()然后返回空指针.
用法:
int main() {
Stack<int> stack;
//fill stack somehow
int val;
stack.pop(val); //val will be set to the popped item, or unchanged if the stack was empty
// You can also use the return value to access the popped item:
std::cout << *stack.pop(val);
// ... or use it to test whether the pop() succeeeded
if (stack.pop(val)) {
//val was popped, use it
}
}
Run Code Online (Sandbox Code Playgroud)