Item9. Choose carefully among easing options.
一、删除特定值
对于
vector
、string
或deque
最好使用
erase-remove
习惯用法:1
c.erase(remove(c.begin(), c.end(), 1963, c.end()));
对于
list
容器直接使用
remove
方法:1
c.remove(1963);
对于标准关联容器
直接使用
erase
方法:1
c.erase(1963)
二、删除满足特定判定条件的值
1 | bool badValue(int) { return true; } // 返回x是否为"坏值" |
对于
vector
、string
或deque
使用erase-remove-if
方法:1
c.erase(remove_if(c.begin(), c.end(), badValue, c.end()));
对于
list
容器
直接使用remove_if
方法:1
c.remove_if(badValue);
对于标准关联容器
把当前的i传给erase,i后缀递增
1
2
3
4for (AssocContainer<int>::iterator i = c.begin(); i != c.end();) {
if (badValue(*i)) c3.erase(i++);
else ++i;
}
三、循环内部删除对象之外还要做某些事
1 | void doSomething(int) { ... } |
对于
vector
、string
或deque
接收
erase
返回的迭代器值。1
2
3
4
5
6for (SeqContainer<int>::iterator i = c.begin(); i != c.end();) {
if(badValue(*i)) {
doSomething(*i);
i = c.rease(i);
} else ++i;
}对于
list
容器虽然也可以采用标准关联容器方法,但建议采用跟
vector
、string
或deque
一致。对于标准关联容器
1
2
3
4
5
6for (SeqContainer<int>::iterator i = c.begin(); i != c.end();) {
if(badValue(*i)) {
doSomething(*i);
c.rease(i++);
} else ++i;
}