c++c++17stdreverse-iterator

Erasing last element from a set in C++


    #include <bits/stdc++.h>
    #define FIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
    #define SZ(s) int(s.size())
    using namespace std;
    typedef long long ll;
    int main()
    {
        FIN;
        set<ll>s;
        ll N, M;
        cin >> N >> M;
        ll x;
        for(ll i = 0; i < N+M; i++)
        {
            cin >> x;
            if(x==-1)
            {
                auto x = *s.rbegin();
                cout<<x<<'\n';
//-------------------------------------------------------------------------------------------------
                s.erase( --s.end() ); // --s.end() when replaced with s.rbegin(), gives an error
//------------------------------------------------------------------------------------------------
            }
            else
            {
                s.insert( x );
            }
        }
        
    }

in the code between the horizontal lines, I am trying to erase last element from the set.

when I write s.erase( s.rbegin( ) ) instead of s.erase( --s.end( ) ) , it gives me a compilation error saying:

 **error: no matching function for call to ‘std::set<long long int>::erase(std::set<long long int>::reverse_iterator)’
   20 |    s.erase( s.rbegin() );**

arent s.rbegin() and --s.end() pointing to the same element?


Solution

  • std::set::rbegin returns a reverse_iterator, which technically points to the same thing, yet the set doesn't have an erase method that receives a reverse_iterator as an argument.