Example: Implementing a Stack data structure Using vector
Here's a C++ program that implements a stack using the vector container. This approach leverages RAII to automatically manage memory, making it safer than a manual stack implementation.
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class Stack {
private:
vector<T> data;
public:
void push(const T& value) {
data.push_back(value);
}
void pop() {
if (!isEmpty()) {
data.pop_back();
}
}
T top() const {
return data.back();
}
bool isEmpty() const {
return data.empty();
}
};
int main() {
Stack<int> myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
myStack.pop();
cout << "Top element: " << myStack.top() << endl;
cout << "Stack empty? " << boolalpha << myStack.isEmpty() << endl;
return 0;
}
* vector: This container is used to store the elements of the stack. It automatically manages memory allocation and deallocation, preventing memory leaks.
* RAII (Resource Acquisition Is Initialization): The vector's destructor is called automatically when it goes out of scope, ensuring that the memory it allocated is freed.
* Template: The Stack class is a template, making it versatile for different data types.
* Safe Operations: The push, pop, and top functions are designed to be safe. They check for empty conditions before performing operations to avoid undefined behavior.
C++ Key Safety Features:
* Memory Management: vector handles memory allocation and deallocation automatically.
* Exception Safety: The Stack class can be made exception-safe by using techniques like RAII and proper exception handling.
* Range-Based For Loops: Consider using range-based for loops for iterating over elements in a safer and more concise manner.
* Move Semantics: For performance, especially with large objects, consider using move semantics to avoid unnecessary copies.
* Custom Allocators: For specific memory management needs, you can provide a custom allocator to vector.
By following these practices, you can write more safe and more reliable C++ code.
No comments:
Post a Comment