Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using set.insert( key ) as a conditional?

I am trying to use set.insert (key) as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like:

if (set.insert( key )) {
    // some kind of code
}

Is this allowed? Because the compiler is throwing this error:

conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal
like image 814
Tomek Avatar asked Oct 21 '08 03:10

Tomek


1 Answers

The version of insert that takes a single key value should return a std::pair<iterator,bool>, where the bool indicates whether an insertion was made. A value of true indicates that the value was inserted, and false indicates that the value was already present. So your conditional would look like this:

if( set.insert( key ).second ) {
      // code
}
like image 175
Charlie Avatar answered Oct 11 '22 13:10

Charlie