Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the pair in the set using first element of the pair only?

Tags:

c++

set

Hello I have a set of pair which contains the following elements.

set < pair<int,int> >st;
st.insert(make_pair(1,2));
st.insert(make_pair(4,5));
st.insert(make_pair(7,8));

Now I want to delete the pair from the set based on first element of the pair using set.erase().?

In - {(1,2),(4,5),{7,8}}
To achieve -  set.erase({1}).
out- {(4,5),(7,8)} // removing member of set using first element of pair.

Please help to achieve this. Thanks in advance !!!

like image 664
ashwani tiwari Avatar asked Oct 24 '25 15:10

ashwani tiwari


2 Answers

If you want to delete an element using erase method, you need to get iterator to removed position, use find_if algorithm with predicate to find element, and pass this iterator to erase method.

    auto it = std::find_if(st.begin(), st.end(), [](const pair<int,int>& p ){ return p.first == 1; });
    if (it != st.end())
        st.erase(it);
like image 97
rafix07 Avatar answered Oct 26 '25 05:10

rafix07


std::map is perfect fit for your need. There is erase by key method on map.

But if you really need to use set, use standard algorithm to find element and then use erase on set using iterator returned by find_if algorithm.

like image 31
Elvis Oric Avatar answered Oct 26 '25 05:10

Elvis Oric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!