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

ぐ巨炮叔叔 提交于 2019-12-02 17:49:51
user2251346
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.

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.

Arun

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

We can do something like this:

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

In fact, the correct answer is:

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

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