1,刪除一個元素
比如:vector vecID; 中儲存了m個ID,這時要刪除第n個ID。
遍曆是一個方法;即vector::itertor it = vecID.begin(); 然後++it n次。
更好的方法是:vector::itertor it = vecID.begin() + n; vector的迭代器直接支援這種位移。
然後用vecID.erase(it)方法 刪除該元素。
2.去除一個容器中有特定值的所有對象
1)如果容器是vector、string或deque,使用erase-remove慣用法,例如
c.erase(remove(c.begin(), c.end(), 1963),c.end());
2)如果容器是list,使用list.remove
// 當c是list時,remove成員函數是去除特定值的元素的最佳方法
c.remove(1963);
3)如果容器是標準關聯容器,使用它的erase成員函數,例如:
// 當c是標準關聯容器時,erase成員函數是去除特定值的元素的最佳方法
c.erase(1963);
3.去除一個容器中滿足一個特定判定式的所有對象
bool badValue(int x); // 函數定義:返回x是否是“bad”
o 如果容器是vector、string或deque,使用erase-remove_if慣用法:
// 當c是vector、string或deque時這是去掉badValue返回真的對象的最佳方法
c.erase(remove_if(c.begin(), c.end(), badValue),c.end());
o 如果容器是list,使用list.remove_if:
// 當c是list時這是去掉badValue返回真的對象的最佳方法
c.remove_if(badValue);
o 如果容器是標準關聯容器,使用remove_copy_if和swap。
o 如果需要寫一個迴圈遍曆容器元素erase,注意iterator的遞增邏輯
// 錯誤碼:當容器的一個元素被刪時,指向那個元素的所有迭代器都失效了
AssocContainer<int> c;
// 不要這麼做!
for (AssocContainer<int>::iterator i = c.begin(); i!= c.end(); ++i)
{
if (badValue(*i))
{
c.erase(i);
}
}
// 正確代碼:
AssocContainer<int> c;
// for迴圈的第三部分是空的,i在後面自增。
for (AssocContainer<int>::iterator i = c.begin(); i != c.end();)
{
if (badValue(*i))
{
i = c.erase(i); //僅適用序列容器,關聯容器用c.erase(i++); 因關聯容器erase 返回void,
}
else
{
++i;
}
}(#add 妙哉)