2 years ago

#39397

test-img

Ayush Gupta

How set is different from unordered_set in c++?

I was solving a problem where I have to find the number of distinct numbers so I used unordered_set and insert the given elements in the set, then I printed the size of the set.


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin>>n;
    unordered_set<int> set;
    int temp;
    for(int i=0; i<n; i++)
    {
        cin>>temp;
        set.insert(temp);
    }
    cout<<set.size()<<endl;
    return 0;
}

But in a few test cases, it shows TLE. So I changed the unoreded_set to set and it worked.

I was searching on the internet how insertion works in set and unordered_set and how their time complexity varies in different operations but was not able to find satisfying answer.

c++

set

unordered-set

0 Answers

Your Answer

Accepted video resources