c++ - 我的 pop 函数应该采用什么参数?

标签 c++ templates stack

这是我的功能,

    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/

相关文章:

c++ - 在 C++ 中停止 python 对象超出范围

c++ - 如何在C++中从成对的排序 vector 中获得与给定值有关的相应对

arrays - 在 Julia 中按列堆叠数组

C++对象返回

c++ - std::find_if 中的编译错误

wpf - TreeViewItem - 一起使用 ControlTemplate 和 HierarchicalDataTemplate

c++ - int a[5]和int(&a)[5]在模板参数推导上的区别

templates - xslt 条件增量

java - 从字符堆栈构造字符串的高效简洁方法是什么

c - 大批。访问 0xFFFFFFFF 元素