2

这是我的功能,

    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。据我了解,pop 函数不应该真的可以选择从堆栈中弹出什么。后进先出对吗?主要问题是 Keytype& x 参数到底是什么,你将如何在 main 中调用它?(在这种情况下,KeyType 在此特定程序中被初始化为 KeyType *stack an int)。

4

5 回答 5

5

这是一个非常奇怪的设计功能。

Stack是一个类模板,由存储在堆栈中的类型参数化(KeyType出于某种原因命名)。该函数采用类型引用的输出参数 ,如果堆栈不为空,则将弹出的值分配给. 同时,它返回它的地址(它返回一个指向 的指针)。如果调用时堆栈为空,它将调用然后返回一个空指针。xKeyTypexKeyTypepop()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
  }
}
于 2013-10-14T07:16:15.533 回答
0

它填充弹出项的值

int main(..)
{

   ...
   int poppedItem;

  stack.pop(poppedItem);
}
于 2013-10-14T07:14:15.510 回答
0

如果KeyType参数是int你所说的,那么你Stack可能看起来像这样:

Stack<int> stack;

方法中的&符号Pop意味着您传入了(在您的情况下)的引用。也就是说,该方法不仅返回弹出项的值,而且将值放入传递的参数中。KeyTypeintPop

int a, b;
a = *(stack.pop(b));
cout << a << " = " << b << endl;
于 2013-10-14T07:15:41.280 回答
0

变量 x 与返回值相同(只是获取从堆栈中排除的顶部元素的其他方式)

Stack<int> my_stack;

// blah-blah-blah ...

int tmp;
int* tmp_pointer = my_stack.pop(tmp);
some_func(tmp);
some_other_func(*tmp_pointer);

// tmp_pointer == &tmp;  
// you can use one of two ways
于 2013-10-14T07:18:32.840 回答
0

据我了解,该函数采用 keytype 的任何元素并检索引用。

所以打电话

int value = 0; 
Pop(value);

用 &value 调用 Pop - 所以实际上是用 int 值的地址,因此是通过引用。

我想知道return 0如果您使用任何非数字数据类型调用 Pop,编译器可能会告诉您,return 语句无效。也许返回 NULL 会更好。(至少更好读)

于 2013-10-14T07:20:43.787 回答