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 !!!
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With