set erase() in C++

erase(): This function is a build-in function in STL.This function erases

elements according to the provided key. This function returns the number of elements erased. This function erases all the elements located by the given key from a set. 

Note: This function only erases the element and that if the element is itself a pointer, 

the pointed-to memory is not touched in any way. 

Parameters:

 __x – Key of the element to be erased. 

Syntax:

st.erase(__x)

For Example:

st = {1,2,3,4}

st.erase(3) = > It erases 3 from the set. So after erasing 3 from set , set becomes = {1,2,4}

Approach

C++

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

int main()
{
    set<intst;
    st.insert(4);
    st.insert(2);
    st.insert(3);
    st.insert(1);

    //remove 3 from the set
    st.erase(3);

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

    return 0;
}


No comments:

Post a Comment