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 exsist 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 back at me:

conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal

Thanks in advance,


+2  A: 

set::insert returns a pair, try this:

if( set.insert( key ).second ) {
    // some kind of code
Don Neufeld
+9  A: 

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
+1  A: 

Other answers have suggested just using '.second', and this will work - but if the processing that you need to perform uses the existing entry in the set, then you can store the full result of the insert:

std::pair<std::set<key>::iterator, bool> iResult = set.insert (key);
if (iResult.second) {
    // some kind of code - insert took place
else {
    // some kind of code using iResult.first, which
    // is an iterator to the previous entry in the set.
Richard Corden