【发布时间】:2018-06-03 16:10:11
【问题描述】:
所以我有一个问题正在解决我的大学课程。本质上,教授在头文件和 main() 中给了我们一个模板,他问我们如果我们尝试“cout
#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;
}
我知道我们会得到一个分段错误或类似的东西,因为我们试图访问或 pop() 一个空堆栈。他希望我们只更改 stack.h。我已经添加了:
"void pop() { if (container.size() > 0) container.pop_back(); }"
它适用于 s2.pop()。
我的问题是,当我尝试在该行中添加“if (container.size() > 0)”时:
"T top(){ return container.back(); }"
即使(至少我认为)我在返回之前检查了大小,我仍然会遇到分段错误?我将如何处理这个?在此先感谢:)
【问题讨论】: