Difference between std::set vs std::vector in C++ STL
Vectors: Vectors are containers similar to dynamic arrays with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are traversed using iterators.
vector <int> v; v.push_back(1); v.push_back(2); v.clear();
Below is the implementation of vectors in C++:
Elements in vector are: 11 6 12 0 0
Set: Set is also one of the templates of Standard Template Library or STL. It is a container of unique elements whose value can’t be modified once added to the set but can be deleted or inserted. The elements of the sets are always stored in sorted form.
set <int> s; s.insert(1); s.insert(12); int key = 1; s.erase(key);
Below is the implementation of sets in C++:
Elements in set: 0 6 11 12
Tabular Difference between the vector and set: Vector Set
Elements of the vector are unsorted. Elements of sets are always sorted. It can contain duplicate elements. It contains only unique elements. The vector is unordered. Set is ordered. The time complexity for insertion of a new element is O(1). The time complexity for the insertion of a new element is O(log N). Vector is faster for insertion and deletion of elements at the end of the container. Set is faster for insertion and deletion of elements at the middle of the container.