Set detect insertion failure

01100110 picture 01100110 · Mar 6, 2012 · Viewed 18.2k times · Source

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
}

Answer

Robᵩ picture Robᵩ · Mar 6, 2012

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
}