Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase final member of std::set

Tags:

c++

set

stl

How can I delete the last member from a set?

For example:

set<int> setInt; setInt.insert(1); setInt.insert(4); setInt.insert(3); setInt.insert(2); 

How can I delete 4 from setInt? I tried something like:

 setInt.erase(setInt.rbegin()); 

but I received an error.

like image 383
herzl shemuelian Avatar asked Dec 13 '11 16:12

herzl shemuelian


People also ask

How do you delete an element from a set in C++?

Deleting a single element from the set container is very simple in C++. The idea is to pass the given element to the set::erase function, which erases it from the set.

How do you delete an element from a set?

Python Set remove() MethodThe remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.

How do you remove the last element of a vector?

The C++ function std::vector::pop_back() removes last element from vector and reduces size of vector by one.


2 Answers

in C++11

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

You can decide how you want to handle cases where the set is empty.

like image 122
Benjamin Lindley Avatar answered Oct 03 '22 00:10

Benjamin Lindley


if (!setInt.empty()) {     std::set<int>::iterator it = setInt.end();     --it;     setInt.erase(it); } 

By the way, if you're doing this a lot (adding things to a set in arbitrary order and then removing the top element), you could also take a look at std::priority_queue, see whether that suits your usage.

like image 27
Steve Jessop Avatar answered Oct 03 '22 01:10

Steve Jessop