-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
59 lines (47 loc) · 1.17 KB
/
Copy pathstack.cpp
File metadata and controls
59 lines (47 loc) · 1.17 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
template<typename T>
class Stack{
private:
vector<T> stack;
public:
void push(const T& value){
stack.push_back(value);
}
void pop(){
if(isEmpty()){
throw runtime_error("Stack underflow: Attempt to pop from an empty stack.");
}
stack.pop_back();
}
T top() const{
if (isEmpty()) {
throw runtime_error("Stack underflow: Attempt to access top of an empty stack.");
}
return stack.back();
}
bool isEmpty() const{
return stack.empty();
}
size_t size() const{
return stack.size();
}
};
int main() {
Stack<int> s;
s.push(10);
s.push(20);
s.push(30);
cout << "Top element: " << s.top() << endl; // Output: 30
cout << "Stack size: " << s.size() << endl; // Output: 3
s.pop();
cout << "Top element after pop: " << s.top() << endl; // Output: 20
cout << "Stack size after pop: " << s.size() << endl; // Output: 2
while (!s.isEmpty()) {
cout << "Popping: " << s.top() << endl;
s.pop();
}
return 0;
}