unordered_set erase() in C++

erase(): This function is available in the File: unordered_set.h

Syntax:

std::unordered_set<int>::iterator std::unordered_set<int>::erase(std::unordered_set<int>::iterator __position)

This function takes one argument Iterator as its parameter. This function erases elements according to the provided position.

Parameters: One parameter is required for this function.

__position – Iterator of the element to be erased.

File: unordered_set.h

Approach 1: When the function erases by position.

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_set<intst = {9563445};
    unordered_set<int>::iterator __position = st.begin();

    //erase by position
    st.erase(__position);

    for (auto it = st.begin(); it != st.end(); it++)
        cout << *it << " ";
    return 0;
}

Output:

34 6 5 9


Approach 2: When the function erases by value.

Syntax:

std::size_t std::unordered_set<int>::erase(const int &__x)

This function takes one argument value as its parameter. This function erases elements according to the provided key.

Parameters: One parameter is required for this function.

__x – Key of the element to be erased.

Returns: The number of elements erased. This function erases all the elements located by the given key from an unordered_set. For an unordered_set, the result of this function can only be 0 (not present) or 1 (present). 

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_set<intst = {9563445};
    int value = 6;

    //erase by value
    st.erase(value);

    for (auto it = st.begin(); it != st.end(); it++)
        cout << *it << " ";
    return 0;
}

Output:

45 34 5 9


Approach 3: When erasing the elements in the range.

Syntax:

std::unordered_set<int>::iterator std::unordered_set<int>::erase(std::unordered_set<int>::const_iterator __first, std::unordered_set<int>::const_iterator __last).

This function takes two arguments of type Iterator as its parameters. This function erases a [__first,__last) range of elements from an unordered_set.

Parameters: Two parameters are required for this function.

__first – Iterator pointing to the start of the range to be erased.

__last – Iterator pointing to the end of the range to be erased.

Returns: The iterator __last. This function erases a sequence of elements from an unordered_set.

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_set<intst = {95634457812};

    unordered_set<int>::iterator start = st.find(34);
    unordered_set<int>::iterator end = st.end();

    //erase by range
    st.erase(startend);

    for (auto it = st.begin(); it != st.end(); it++)
        cout << *it << " ";
    return 0;
}

Output:

12 78 45

No comments:

Post a Comment