admin管理员组

文章数量:1596253

To eliminate all objects in a container that have a particular value:

contiguous-memory container(vector, deque, or staing)

c.erase(remove(c.begin(), c.eng(), 1963), c.end());

list

c.remove(1963);

associative container

c.erase(1963);

To eliminate all objects in a container that satisfy a particular predicate:

bool badValue(int x);

vector, string or deque

c.erase(remove_if(c.begin(), c.end(), badValue), c.end());

list

c.remove_if(c.begin(), ce.end(), badValue);

associative containers

AssocContainer<int> goodValues;
remove_copy_if(c.begin(), c.end(), inserter(goodValues, goodValues.end()), badValue);
c.swap(goodValues);

To do something inside the loop(in additon to ereasing objects):

Sequence Container

for (SeqContainer<int>::iterator i = c.begin(); i != c.end();) {
    if (badValue(*i)) {
        logFile << "Erasing" << *i << '\n';
        i = c.erase(i);
        }
        elese ++i;
    }
}

Associative Container

ofstream logFile;
AssocContainer<int>c;
...
for(AssocContainer<int>::iterator i = c.begin(); i !=c.end();) {
    if(badValue(*i) {
        logFile << "Erasing" << *i << '\n';
        c.erease(i++);
        }
        else ++i;
    }
}

list
both approaches works for list

本文标签: stlEffectiveOptionserasing