0

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 ?

Arpit
  • 448
  • 8
  • 26
  • 1
    Possible duplicate of [How to call erase with a reverse iterator](https://stackoverflow.com/questions/1830158/how-to-call-erase-with-a-reverse-iterator) – Nicol Bolas Nov 11 '17 at 17:07

1 Answers1

3

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.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • Thanks ,but Can you tell me,whats problem with my code ? – Arpit Nov 11 '17 at 14:22
  • I told you - your `.base()` call basically returns `a.end()`. You're then erasing a past-the-end iterator, which is undefined behavior. – Vittorio Romeo Nov 11 '17 at 14:22
  • Okay i got it but if I pass directly, "a.erase(it)" then also doesn't work ? even though i am passing reference for a element that needs to be deleted. – Arpit Nov 11 '17 at 14:26