Stack Implementation in C++
#include <iostream>
#include <stdexcept>
#include <vector>
class Stack {
private:
std::vector<int> items;
public:
bool is_empty() const {
return [Link]();
}
void push(int item) {
items.push_back(item);
}
int pop() {
if (is_empty()) {
throw std::out_of_range("Stack is empty.");
}
int top_item = [Link]();
items.pop_back();
return top_item;
}
int peek() const {
if (is_empty()) {
throw std::out_of_range("Stack is empty.");
}
return [Link]();
}
size_t size() const {
return [Link]();
}
void clear() {
[Link]();
}
void display() const {
for (int item : items) {
std::cout << item << " ";
}
std::cout << std::endl;
}
};
int main() {
Stack stack;
[Link](5);
[Link](15);
[Link](25);
[Link]();
std::cout << "Top: " << [Link]() << std::endl;
std::cout << "Popped: " << [Link]() << std::endl;
std::cout << "Popped: " << [Link]() << std::endl;
[Link]();
std::cout << "Size: " << [Link]() << std::endl;
std::cout << "Empty: " << (stack.is_empty() ? "Yes" : "No") << std::endl;
[Link]();
std::cout << "Stack cleared." << std::endl;
std::cout << "Empty: " << (stack.is_empty() ? "Yes" : "No") << std::endl;
return 0;
}
Output:
5 15 25
Top: 25
Popped: 25
Popped: 15
5
Size: 1
Empty: No
Stack cleared.
Empty: Yes
OOP Properties Used
1. Encapsulation
Encapsulation is achieved by keeping 'items' private and providing public methods to modify the stack safely.
2. Abstraction
Users interact with 'push', 'pop', 'peek', etc., without knowing the internal vector implementation.
3. Inheritance
Though not used here, the Stack class can be extended to create specialized stacks like MinStack or
MaxStack.
4. Polymorphism
Could be implemented using virtual functions if a derived class overrides methods from the Stack class.