Is there a simple way to detect when a set insert does not occur because the item being inserted already exists in the set? For example, I'd like to display a message to the user that shows the insert failure so that they can find and remove the duplicates in their data more easily. Here's some pseudo code to demonstrate what I'd like to do:
try
{
items.insert(item)
}
catch insert_failed_item_already_in_set
{
// show user the failed item
}
An insert operation on a set returns a pair, with its member first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
set insert() function in C++ STL Return Value: The function returns an iterator pointing to the inserted element in the container.
A signature for set::insert
is:
pair<iterator,bool> insert ( const value_type& x );
So, your code would look like:
if( !items.insert(item).second )
{
show user the failed item
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With