Jun 6, 2016 at 9:29pm UTC
So here I have a homework assignment where I was to implement stacks and templates. The program was working fine until I added the s2.pop() at the end of the program. This is where I get my segmentation fault. Any tips on why and how I can fix it? Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <vector>
#include <string>
#include <iostream>
using namespace std;
template <typename T>
class Stack
{
vector<T> container;
public :
Stack(): container() {}
void push(T x) { container.push_back(x); }
void pop() { container.pop_back(); }
T top() { return container.back(); }
bool empty() { return container.empty(); }
};
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();
}
//Error occurs here
s2.pop();
cout << endl;
}
Last edited on Jun 6, 2016 at 9:29pm UTC
Jun 6, 2016 at 9:33pm UTC
You are trying the pop the container when it is already empty.
So you may want to change your pop function to first check if the container is empty, and only pop if it is not empty. It should throw an exception otherwise.
Jun 6, 2016 at 10:02pm UTC
That should work. Fix your braces and formatting though. You have an extra brace floating around in there:
1 2 3 4
void pop() {
if (!container.empty() )
container.pop_back();
}
Last edited on Jun 6, 2016 at 10:03pm UTC
Jun 6, 2016 at 10:07pm UTC
Its the same problem. By the end of that second while, s2 is empty, therefore there is no "top". You are trying to return something nonexistent.
How will you fix this?
Jun 6, 2016 at 10:48pm UTC
Can I just make a 3rd while that does the same thing as the previous 2?
Jun 6, 2016 at 11:28pm UTC
Did and it works now! Thanks for your help really appreciate it.