Question

How to remove the last element from a multiset. I tried passing the reverse iterator to the erase function but that is not allowed. Any suggestions?

Was it helpful?

Solution

Every reverse_iterator has a base() function, that returns "normalized" iterator. You could use it like this:

auto e = ms.rbegin();
ms.erase((++e).base());

We must increment e before getting underlying iterator, because the base iterator refers to the element that is next to the element the reverse_iterator is pointing to.

Another solution is using std::prev function:

ms.erase(std::prev(ms.end())); // since C++11

If C++11 is not an option for you, you could implement it yourself:

// copy-pasted from cppreference
template<class BidirIt>
BidirIt prev(BidirIt it, 
             typename std::iterator_traits<BidirIt>::difference_type n = 1)
{
    std::advance(it, -n);
    return it;
}

It's more simpler, than first, but I leave two solution, because earlier I described first example incorrectly.

OTHER TIPS

If you want to delete only one element then you can write

if ( !ms.empty() ) ms.erase( std::prev( ms.end() ) );

If you want to delete all elements with the given key equal to the last key then you can write

if ( !ms.empty() )
{
    auto p = ms.equal_range( *std::prev( ms.end() ) );
    ms.erase( p.first, p.second );
}

And at last if you want to delete all duplicates except one then you can write

if ( !ms.empty() )
{
    auto p = ms.equal_range( *std::prev( ms.end() ) );
    ms.erase( std::next( p.first ), p.second );
}

Because multiset erase function takes iterator which is regular. So if you want to erase last element you should do like that.

//in C++11
multiset.erase(std::prev(multiset.end()));
//in C++98 
multiset.erase(--multiset.end()); 

You could try the following code:

multiset<int> mySet;

read in some integers.....

multiset<int>::reverse_iterator rit;
rit = mySet.rbegin();

mySet.erase((++rit).base());

the .rbegin() function returns a reverse iterator pointing to the end of the set, rit is then incremented since the base function is currently pointing to the value next to the value we want (credit to @soon for that part, in his answer). The erase() function then erases the element in the parameter.

Hope this helps. =)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top