Question

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
Was it helpful?

Solution

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
}

OTHER TIPS

set::insert returns a pair, try this:

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

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.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top