也许这是一个副本,但我没有找到任何搜索: 在 std::multiset上调用 erase(value)时,删除所有找到值的元素。我能想到的唯一解决办法就是:
std::multiset
erase(value)
std::multiset<int>::iterator hit(mySet.find(5)); if (hit!= mySet.end()) mySet.erase(hit);
这个不错,但我觉得还有更好的办法,有什么主意吗?
I would try the following.
First call equal_range() to find the range of elements that equal to the key.
equal_range()
If the returned range is non-empty, then erase() a range of elements (i.e. the erase() which takes two iterators) where:
erase()
the first argument is the iterator to the 2nd element in the returned range (i.e. one past .first returned) and
.first
the second argument as the returned range pair iterator's .second one.
.second
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 ); }
In fact, the correct answer is:
my_multiset.erase(my_multiset.find(value));
We can do something like this:
multiset<int>::iterator it, it1; it = myset.find(value); it1 = it; it1++; myset.erase (it, it1);
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.
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++
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.
value
This worked for me:
multi_set.erase(multi_set.find(val));
if val exists in the multi-set.
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.
Here is a more elegant solution using "if statement with initializer" introduced in C++17:
if(auto it = mySet.find(value); it != mySet.end()) mySet.erase(value);
The advantage of this syntax is that the scope of the iterator it is reduced to this if statement.
it
if