Open In App

Difference between std::set vs std::vector in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to demonstrate the
// working of vector in cpp
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    vector<int> v;
 
    // Inserting elements in vector
    v.push_back(11);
    v.push_back(6);
    v.push_back(12);
    v.push_back(0);
    v.push_back(0);
 
    // Elements are stored in the
    // order of insertion with the
    // duplicate element
    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++




// C++ program to demonstrate the
// working of set in c++
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    set<int> s;
 
    // Insert elements into the set
    s.insert(11);
    s.insert(6);
    s.insert(12);
    s.insert(0);
 
    // Duplicate elements
    s.insert(0);
 
    cout << "Elements in set:\n";
 
    // The inserted elements get sorted
 
    // Print the elements of the set
    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.
 


Last Updated : 21 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads