In C++, both sets and vectors are part of the Standard Template Library (STL), but they serve different purposes and have different
properties and usage patterns. Here’s a detailed comparison between sets and vectors:
Sets (std::set)
Ordered Collection: Elements in a set are automatically sorted.
Unique Elements: A set does not allow duplicate elements.
Underlying Structure: Typically implemented as a balanced binary search tree (e.g., Red-Black Tree).
Operations:
Insertion: O(log n) time complexity.
Deletion: O(log n) time complexity.
Search: O(log n) time complexity.
Usage:
When you need a collection of unique elements.
When you need the elements to be automatically sorted.
Efficient for lookups, insertions, and deletions.
Vectors (std::vector)
Dynamic Array: Vectors are dynamic arrays, which means they can grow and shrink in size.
Allows Duplicates: Vectors can store duplicate elements.
Underlying Structure: Implemented as a dynamic array.
Operations:
Insertion: O(1) average time complexity for insertion at the end (amortized). O(n) for insertion at an arbitrary position.
Deletion: O(n) for deletion at an arbitrary position.
Search: O(n) for linear search. O(log n) for binary search if the vector is sorted.
Usage:
When you need a collection that can change size frequently.
When you need to access elements by their index.
Suitable for storing elements in a specific order and when duplicates are allowed.
Comparison Summary
Feature std::set std::vector
Order Elements are sorted Elements are in insertion order
Duplicates No Yes
Insertion O(log n) O(1) (end), O(n) (arbitrary)
Deletion O(log n) O(n)
Search `O(log)
To embed this project on your website, copy the following code and paste it into your website's HTML: