【问题标题】:What parameter should my pop function take?我的 pop 函数应该采用什么参数?
【发布时间】:2013-10-14 07:09:25
【问题描述】:

这是我的功能,

    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 在这个特定的程序中)。

【问题讨论】:

  • 实际上 Stack 的 Pop 方法不应该接受任何参数,因为它总是返回堆栈中最顶部的元素,因为它是一个后进先出数据结构。我认为您的 Pop 方法将返回指向 Stack 顶部元素的指针以及值本身;第一个作为返回值,后者通过引用传递。
  • 它实际上不是一个堆栈,它是一个使用类的堆栈实现,可能应该把它放在那里的某个地方,但这是在一个教师给我们的头文件中,所以我假设它是可行的.我一直在争论是否只删除参数哈哈。

标签: c++ templates stack


【解决方案1】:

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

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
  }
}

【讨论】:

  • 谢谢您的解释,先生,是的,我根本不会那样设置它,它只是我们的老师给我们的一个基本堆栈模板的一部分,用于我们在其中的家庭作业必须做其他功能,我无法理解它。
【解决方案2】:

填充弹出项的值

int main(..)
{

   ...
   int poppedItem;

  stack.pop(poppedItem);
}

【讨论】:

    【解决方案3】:

    如果KeyType 参数是您所说的int,那么您的Stack 可能如下所示:

    Stack<int> stack;
    

    Pop 方法中的 & 符号表示您传入 KeyType(在您的情况下为 int)的引用。也就是说,Pop 方法不仅会返回弹出项的值,还会将值放入传递的参数中。

    int a, b;
    a = *(stack.pop(b));
    cout << a << " = " << b << endl;
    

    【讨论】:

      【解决方案4】:

      变量 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
      

      【讨论】:

        【解决方案5】:

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

        打电话来

        int value = 0; 
        Pop(value);
        

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

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

        【讨论】:

          猜你喜欢
          • 2019-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-21
          • 2021-12-06
          • 2021-05-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多