Search code examples
c++c++11stdset

What is the best way to change a set during iterations?


Given std::set , what is the best way to change the set during time-iteration?
For example:

std::set<T> s;  // T is a some type (it's not important for the question).
// insertions to s
for (std::set<T>::iterator it = s.begin(); it != s.end(); it++) {
        T saveIt(*it);
        s.erase(*it);
        s.insert( saveIt + saveIt );  // operator+ that defined at `T`
}

According to what that I read in some sources, it's bad way because that: the removing from the set may change the structure of the set.

So what is the better (/best) way to do it?


Solution

  • Just have a copy std:set

    std::set<T> s;
    std::set<T> modified_s;
    for (std::set<T>::iterator it = s.begin(); it != s.end(); it++) {
        modified_s.insert(*it+ *it);
    }
    s = std::move(modified_s);
    

    Edit: Added std::move as improvement from @Jodocus