In std::multiset is there a function or algorithm to erase just one sample (unicate or duplicate) if an element is found

萝らか妹 提交于 2019-12-03 04:02:26

问题


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 ?


回答1:


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.




回答2:


Try this one:

multiset<int> s;
s.erase(s.lower_bound(value));

As long as you can ensure that the value exits in the set. That works.




回答3:


 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++




回答4:


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 );
}



回答5:


We can do something like this:

multiset<int>::iterator it, it1;
it = myset.find(value);
it1 = it;
it1++;
myset.erase (it, it1);



回答6:


In fact, the correct answer is:

my_multiset.erase(my_multiset.find(value));



来源:https://stackoverflow.com/questions/9167745/in-stdmultiset-is-there-a-function-or-algorithm-to-erase-just-one-sample-unic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!