首页 > 解决方案 > 为 Stack 实现通用集合

问题描述

在创建堆栈时指定数据类型时,我遇到了两种不同的实现。

stack<string>* stringStack = new Stack<string>();

Stack<string> stringStack = new Stack<string>();

指针对堆栈有什么作用?

例如,我的教授为我们提供了代码:

stack<std::string>* stringStack = new Stack<std::string>();

stringStack->push(“Jim”);
std::string top = stringStack->peek();
std::cout << top << “ is at the top of the stack \n”;

在这里,我的教授使用了第一个场景。

当我在网上搜索解决方案时,我找到了代码

Stack<string> stringStack = new Stack<string>();
stringStack.push(17);        
int a = stringStack.pop(); 

我很困惑有什么区别。如果有人可以向我解释有什么区别,如果有或没有,那就太好了!

标签: c++pointersstack

解决方案


当我在网上搜索解决方案时

那就是你的问题。不要去网上搜索和复制/粘贴你不明白的代码。那是你毕业之后。

我找到了代码

Stack<string> stringStack = new Stack<string>();
stringStack.push(17);        
int a = stringStack.pop();

那不会编译。 new用于进行动态分配,并返回一个指针。您在左侧 ( Stack<string> stringStack) 上拥有的不是指针。

*您看到注释左侧的“神秘” (在正确的代码中)表示一个指针。当它不是类型的一部分时,它是一个解引用运算符,这意味着“查找此指针指向的内容”。

动态内存分配必须成对完成... anew和 a delete,否则会泄漏。简要说明:

{ // a scope begins
   int x = 10; // not a pointer; stack allocated
} // a scope ends, integer automatically is gone

{ // a scope begins
   int *px = new int; // px points to integer-sized memory box
   *px = 10; // put 10 into that box
} // a scope ends, you didn't delete px, you leaked memory

这里讨论了是否应该动态分配一些东西的问题,也许你会从中发现一些有价值的东西:

为什么我应该使用指针而不是对象本身?

但是让你更加困惑的是,如果你的教授真的在教“现代 C++”,那么你会被警告不要随意使用原始指针:

什么是智能指针,我应该什么时候使用它?

我要重申,你能为自己做的最好的事情就是不要试图通过在 Internet 上搜索解决方案来走捷径。从一开始就关注你的课程,如果你觉得你的课程或教授有不足,那么通过自己阅读一本好书来补充你的教育。


推荐阅读