In std::multiset is there a function or algorithm to erase just one sample (unicate or duplicate) if an element is found
C++StlMultisetC++ Problem Overview
Perhaps this is a duplicate but I did not find anything searching:
When erase(value)
is called on std::multiset
all elements with the value found are deleted. The only solution I could think of is:
std::multiset<int>::iterator hit(mySet.find(5));
if (hit!= mySet.end()) mySet.erase(hit);
This is ok but I thought there might be better. Any Ideas ?
C++ Solutions
Solution 1 - C++
auto itr = my_multiset.find(value);
if(itr!=my_multiset.end()){
my_multiset.erase(itr);
}
I would imagine there is a cleaner way of accomplishing the same. But this gets the job done.
Solution 2 - C++
Try this one:
multiset<int> s;
s.erase(s.lower_bound(value));
As long as you can ensure that the value
exists in the set. That works.
Solution 3 - C++
if(my_multiset.find(key)!=my_multiset.end())
my_multiset.erase(my_multiset.equal_range(key).first);
This is the best way i can think of to remove a single instance in a multiset in c++
Solution 4 - C++
I would try the following.
First call equal_range()
to find the range of elements that equal to the key.
If the returned range is non-empty, then erase()
a range of elements (i.e. the erase()
which takes two iterators) where:
-
the first argument is the iterator to the 2nd element in the returned range (i.e. one past
.first
returned) and -
the second argument as the returned range pair iterator's
.second
one.
Edit after reading templatetypedef's (Thanks!) comment:
If one (as opposed to all) duplicate is supposed to be removed: If the pair returned by equal_range()
has at least two elements, then erase()
the first element by passing the the .first of the returned pair to single iterator version of the erase()
:
Pseudo-code:
pair<iterator, iterator> pit = mymultiset.equal_range( key );
if( distance( pit.first, pit.second ) >= 2 ) {
mymultiset.erase( pit.first );
}
Solution 5 - C++
This worked for me:
multi_set.erase(multi_set.find(val));
if val exists in the multi-set.
Solution 6 - C++
We can do something like this:
multiset<int>::iterator it, it1;
it = myset.find(value);
it1 = it;
it1++;
myset.erase (it, it1);
Solution 7 - C++
auto itr=ms.find(value);
while(*itr==value){
ms.erase(value);
itr=ms.find(value);
}
Try this one It will remove all the duplicates available in the multiset.
Solution 8 - C++
In fact, the correct answer is:
my_multiset.erase(my_multiset.find(value));