Stack Example
tuhuuduc
c_cpp
2 years ago
1.1 kB
8
Indexable
#include <iostream>
#include <vector>
template <typename T>
class Stack {
private:
std::vector<T> elements;
public:
// Push element onto the stack
void push(const T& element) {
elements.push_back(element);
}
// Pop element from the stack
void pop() {
if (!elements.empty()) {
elements.pop_back();
} else {
std::cerr << "Stack is empty. Cannot pop." << std::endl;
}
}
// Get the top element of the stack
T& top() {
if (!elements.empty()) {
return elements.back();
} else {
std::cerr << "Stack is empty." << std::endl;
// Returning a reference to the first element
// This is not a safe operation, but done here for demonstration purposes
return elements.front();
}
}
// Check if the stack is empty
bool empty() const {
return elements.empty();
}
// Get the size of the stack
size_t size() const {
return elements.size();
}
};Editor is loading...
Leave a Comment