You can directly delete iterators while looping through associative containers like set and map:


    for(auto itue = usersByEmail_.begin(), itue_end = usersBySecret_.end(); itue != itue_end; ) 
    {
        if ((*itue)->bDeleted())
        { 
            // NOTE We could do more cleanup work here if needed.
            itue = usersByEmail_.erase(itue);

        } else ++itue;
    }

With sequential containers like vector, you should use the erase-remove idiom. Here’s an example for my multi-indexed sets of pointers that uses a lambda to keep the code tight. runsByRank_ is of my sorted_vector type:


    runsByRank_.erase(
        remove_if(
            runsByRank_.begin(), runsByRank_.end(),    
            []( StockRun*& psr )
            { 
                // NOTE We could do more cleanup work here if needed.
                return psr->bDeleted(); 
            }
        ),
        runsByRank_.end()
    );

I’ll try to get my quick-http skeleton app updated with these best practices soon. As of now it does not include any delayed-deletion pattern.

Leave a Reply