2

如何从多重集中删除最后一个元素。我尝试将反向迭代器传递给擦除函数,但这是不允许的。有什么建议么?

4

4 回答 4

5

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.

于 2013-10-19T17:32:55.407 回答
1

如果你只想删除一个元素,那么你可以写

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

如果要删除给定键等于最后一个键的所有元素,则可以编写

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

最后,如果您想删除除一个以外的所有重复项,则可以编写

if ( !ms.empty() )
{
    auto p = ms.equal_range( *std::prev( ms.end() ) );
    ms.erase( std::next( p.first ), p.second );
}
于 2013-10-19T18:01:18.277 回答
0

您可以尝试以下代码:

multiset<int> mySet;

读入一些整数......

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

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

.rbegin() 函数返回一个指向集合末尾的反向迭代器,然后增加 rit ,因为基函数当前指向我们想要的值旁边的值(在他的回答中,这部分归功于@soon )。然后,erase() 函数会擦除参数中的元素。

希望这可以帮助。=)

于 2013-10-19T17:46:11.857 回答
0

因为多集擦除功能采用常规的迭代器。所以如果你想删除最后一个元素,你应该这样做。

//in C++11
multiset.erase(std::prev(multiset.end()));
//in C++98 
multiset.erase(--multiset.end()); 
于 2013-10-19T17:41:51.683 回答