C++ data structure and containers and their operation with time complexity
C++ provides a rich set of data structures and containers in its Standard Library, particularly within the <vector>, <list>, <deque>, <set>, <map>, <unordered_set>, and <unordered_map> headers. Here is a summary of some of the key data structures, their operations, and the associated time complexities:
- Vector (`std::vector`)
- Access: O(1) for random access using `operator[]` or `at()`.
- Insertion/Deletion at End: Amortized O(1) for `push_back()`, O(1) for `pop_back()`.
- Insertion/Deletion at Beginning or Middle: O(n).
- Search: O(n) for linear search. - List (`std::list`)
- Access: O(n) for random access (lists do not support direct access).
- Insertion/Deletion at Beginning or Middle: O(1) (constant time since it is a doubly linked list).
- Search: O(n) for linear search. - Deque (`std::deque`)
- Access: O(1) for random access using `operator[]` or `at()`.
- Insertion/Deletion at End: O(1) for `push_back()` and `pop_back()`.
- Insertion/Deletion at Beginning: O(1) for `push_front()` and `pop_front()`.
- Insertion/Deletion in the Middle: O(n).
- Search: O(n) for linear search. - Set (`std::set`)
- Access: O(log n) (sets do not support direct access).
- Insertion/Deletion: O(log n).
- Search: O(log n). - Unordered Set (`std::unordered_set`)
- Access: N/A (unordered sets do not support direct access).
- Insertion/Deletion: O(1) on average, O(n) in worst case.
- Search: O(1) on average, O(n) in worst case. - Map (`std::map`)
- Access: O(log n) using `operator[]` or `at()`.
- Insertion/Deletion: O(log n).
- Search: O(log n). - Unordered Map (`std::unordered_map`)
- Access: O(1) on average using `operator[]` or `at()`, O(n) in worst case.
- Insertion/Deletion: O(1) on average, O(n) in worst case.
- Search: O(1) on average, O(n) in worst case. - Stack (`std::stack` - typically implemented using `std::deque` or `std::vector`)
- Access: N/A (stacks do not support direct access).
- Push: O(1).
- Pop: O(1).
- Top: O(1). - Queue (`std::queue` - typically implemented using `std::deque` or `std::list`)
- Access: N/A (queues do not support direct access).
- Push: O(1).
- Pop: O(1).
- Front/Back: O(1). - Priority Queue (`std::priority_queue`)
- Access: O(1) to access the top element.
- Insertion: O(log n).
- Deletion (Pop): O(log n).
These time complexities help in choosing the right container for a specific use case, balancing between efficiency of various operations such as access, insertion, deletion, and search.
Comments
Post a Comment