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.
Examples:
vector <int> v;
v.push_back(1);
v.push_back(2);
v.clear();
Below is the implementation of vectors in C++:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > v;
v.push_back(11);
v.push_back(6);
v.push_back(12);
v.push_back(0);
v.push_back(0);
cout << "Elements in vector are:\n" ;
for ( auto it : v) {
cout << it << " " ;
}
return 0;
}
|
Output:
Elements in vector are:
11 6 12 0 0
Time Complexity: O(N) // For N insertions
Auxiliary Space: O(1)
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.
Examples:
set <int> s;
s.insert(1);
s.insert(12);
int key = 1;
s.erase(key);
Below is the implementation of sets in C++:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(11);
s.insert(6);
s.insert(12);
s.insert(0);
s.insert(0);
cout << "Elements in set:\n" ;
for ( auto it : s) {
cout << it << " " ;
}
return 0;
}
|
Output:
Elements in set:
0 6 11 12
Time Complexity: O(Nlog N) // For N insertions
Auxiliary Space: O(1)
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. |
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Jun, 2022
Like Article
Save Article