tags:

views:

101

answers:

4

can you get the last or newly added element in std::set? for example say if the loop runs to collect the elements to fill in the std::set.

if on the first run the set was,

[0] "A"
[1] "B"
[2] "D"

and, on second run, the set becomes

[0] "A"
[1] "B"
[2] "C"
[3] "D"

How would you check if 'C' is the new element that was added?

+5  A: 

If you still have the old set, compute the set_difference between them.

Otherwise, you can't. The std::set doesn't retain any information about when the element is inserted. Use a std::vector (and insert elements by push_back only) if you need to keep that information.

KennyTM
A: 

sets are different from lists and vectors in that they are unordered. Adding an object to the set will put it somewhere in the set, but not necessarily at the end.

see cplusplus/set for more information about the way a set stores its information

mathieu Van den Berghe
+10  A: 

set::insert returns an iterator to the newly inserted item. Hold on to that iterator if you're interested in that item.

Jon-Eric
A: 

IMHO, easiest could be storing the last inserted value in a variable, see the "Memento" design pattern. Another way is to use another data structure - maybe some sort of stack.

Gabriel Ščerbák