Re: Deleting the last element of an std::set
On Jun 28, 5:21 pm, "Bo Persson" <b...@gmb.dk> wrote:
Giuliano Bertoletti wrote:
another question: I wish to erase the last element of a set
(last according to some custom less operator I have defined
for that set).
Is the following code correct ?
What worries me most is the --hi.end() construct.
std::set< sometype > hi;
if(!hi.empty()) {
hi.erase( --hi.end() );
}
The potential problem is that if the iterator is actually a
raw pointer (could be for std::vector, but hardly for a
std::set), you cannot decrement the temporary returned by
end(). If the iterator is a class with an operator--() member
function, is will be ok.
And if the iterator is a class with a non-member operator--()
function, it won't be OK.
So, in practice, if the code compiles it works for the
container you are using.
IF the code compilers. (Formally, of course, it's undefined
behavior, but in practice, either it will compile and work, or
it will fail to compile.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34