vendredi 30 décembre 2016

how to delete adjacent entries from a set while iterating over it

How can I erase all adjacent entries from a set while iterating over the set. In my case I have a custom comparator that defines adjacent entries as those that differ by 1 from left to right. Thus for the set std::set<int> mySet = {1,2,3,4,5,7,9,10} I would like to remove the entries {1,2,3,4,5,9,10} as these satisfy my comparator. (note the 7 is left as it is the only one in the series is not one of the elements in an adjacent pair.

The code below (also in coliru) shows that I can find add the adjacent entries correctly, however if I try to erase both the left side of the adjacent pair adjIter and also the right side *std::next(adjIter) the code crashes with an invalid iterator.

int main() {    
    std::set<int> mySet = {1,2,3,4,5,7,9,10};
    static const auto gPred = [](const auto& lhs, const auto& rhs) {
        return rhs == lhs+1;
    };
    auto adjIter = mySet.begin();
    std::set<int> adjacentEntries;
    while ((adjIter = std::adjacent_find(adjIter, mySet.end(),
        gPred)) != mySet.end()) {
        adjacentEntries.insert(*adjIter);
        // peek at the second entry that should be 1 greater than adjIter        
        adjacentEntries.insert(*std::next(adjIter));
        // how do I erase both *std::next(adjIter) & adjIter
        ++adjIter;
    }
    std::cout << adjacentEntries << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire