How to delete last element from a set in C++

C++Server Side ProgrammingProgramming

Suppose we have one STL set in C++. There are few elements. We have to delete the last element from that set. So if the elements are like [10, 41, 54, 20, 23, 69, 84, 75], then the set will be like [10 20 23 41 54 69 75 84], and last element is 84. We will see the C++ code to delete last element from set.

Example

 Live Demo

#include<iostream>
#include<set>
using namespace std;
void display(set<int> my_set){
   for (auto it = my_set.begin(); it != my_set.end(); ++it)
   cout << *it << " ";
}
int main() {
   int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};
   int n = sizeof(arr)/sizeof(arr[0]);
   set<int> my_set;
   for(int i = 0; i<n; i++){
      my_set.insert(arr[i]);
   }
   cout << "Set before delete: ";
   display(my_set);
   set<int>::iterator it;
   it = prev(my_set.end());
   my_set.erase(it);
   cout << "\nSet after delete: ";
   display(my_set);
}

Output

Set before delete: 10 20 23 41 54 69 75 84
Set after delete: 10 20 23 41 54 69 75
raja
Published on 17-Dec-2019 12:56:51
Advertisements