所以我有一个问题,我正在为我的大学课程工作。基本上教授给我们一个头文件和一个main()模板,他问我们如果我们试图" cout<< s2.top();"和s2.pop();在多个s2.push()和while循环之后(当堆栈为空时)。我已经明白,在我们对堆栈中的数据进行cout之后,我们会弹出()最后一个元素,直到它为空。这是stack.h的代码:
#ifndef STACK_H
#define STACK_H
#include <vector>
using namespace std;
template <typename T>
class Stack
{
vector<T> container;
public:
Stack(): container() {}
void push(T x) { container.push_back(x); }
void pop() { if (container.size() > 0) container.pop_back(); }
T top(){ if (container.size() > 0) return container.back(); }
bool empty() { return container.empty(); }
};
#endif
这是main():
#include <iostream>
#include <string>
#include "stack.h"
main()
{
Stack<int> s1;
s1.push(4);
s1.push(3);
s1.push(2);
s1.push(1);
while (!s1.empty()) {
cout << s1.top() << endl;
s1.pop();
}
Stack<string> s2;
s2.push("Yoda said ");
s2.push("something ");
s2.push("to write ");
while (!s2.empty()) {
cout << s2.top();
s2.pop();
}
s2.pop();
cout << s2.top();
cout << endl;
}
我知道我们会在尝试访问或弹出()空堆栈时遇到分段错误或类似问题。他希望我们只改变stack.h。我已经添加了:
&#34; void pop(){if(container.size()&gt; 0)container.pop_back(); }&#34;
它适用于s2.pop()。
我的问题是,当我尝试添加&#34; if(container.size()&gt; 0)&#34;在行:
&#34; T top(){return container.back(); }&#34;
即使(至少我认为)我在返回之前检查尺寸,仍然会出现分段错误?我怎么去这个?在此先感谢:)
答案 0 :(得分:2)
如果控件到达返回非void的函数的}
,而不是达到return
,则行为未定义。任何事情都可能发生。
您必须将else
添加到.top()
,并使用它返回某种默认值(您可能需要return {};
),或抛出异常,或阻止该功能以某种其他方式返回。
答案 1 :(得分:1)
您
s2.pop();
cout << s2.top();
循环之外的一个是a)在空容器上调用pop()
(只是愚蠢)。 b)在空容器上调用top()
并使用结果; 错误
当容器为空时,T top(){ if (container.size() > 0) return container.back(); }
也会导致未定义的行为,因为该函数不会返回T
(总是必须)。