tags:

views:

answers:

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:

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:

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.
}