这是我的功能,
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;
}
我的问题是: 我不确定在 main 中如何调用它。据我了解,弹出函数实际上不应该选择从堆栈中弹出什么内容。后进先出对吗?主要问题是 Keytype& x 参数到底采用什么以及如何在 main 中调用它? (在本例中,KeyType 在此特定程序中初始化为 KeyType *stack an int)。
最佳答案
这是一个设计非常奇怪的函数。
Stack
是一个类模板,由存储在堆栈上的类型参数化(由于某种原因命名为 KeyType
)。该函数采用对 KeyType
类型引用的输出参数 x
,如果堆栈不为空,则将弹出的值分配给 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
}
}
关于c++ - 我的 pop 函数应该采用什么参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19355088/