Arpit
Arpit

Reputation: 478

How to erase element with a reverse iterator from a `std::set`?

Facing issue with deletion of last element in set :

#include <bits/stdc++.h>
using namespace std;
int main()
{
set < pair <int,int > > a;
a.insert(make_pair(2,3)); 
auto it = a.rbegin();
a.erase(it.base()); // for deleting last element in set
cout << a.size() << endl;
return 0; 
}

Getting the runtime issue, Also have tried with auto, Iterator and Const iterator, it's not working.Is there any other way to erase an element from a set ?

Edit : How can I delete a Particular element based on iterator reference ? if i do like :

auto it=a.begin(); a.erase(it); Here it = reference to the element for deletion

it doesn't work.Any other way to delete based on iterator reference ?

Upvotes: 0

Views: 928

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

Is there any other way to erase an element from a set ?

a.erase(std::prev(std::end(a)));

Can you tell me,whats problem with my code ?

itr.base() where itr == a.begin() is equivalent to a.end(). See: http://en.cppreference.com/w/cpp/iterator/reverse_iterator/base

Erasing a past-the-end iterator is undefined behavior.

Upvotes: 3

Related Questions