跳轉到內容

更多 C++ 慣用法/Erase-Remove

來自 Wikibooks,開放世界中的開放書籍

Erase-Remove

[編輯 | 編輯原始碼]

從 STL 容器中消除元素,以減小其大小。

也稱為

[編輯 | 編輯原始碼]

Remove-Erase(基於執行順序,而不是原始碼行上的型別化順序)

std::remove 演算法不會從容器中消除元素;它只是將未被移除的元素移動到容器的開頭,並將容器末尾的內容保留為未定義。這是因為 std::remove 演算法僅使用一對正向迭代器(迭代器對 慣用法)工作,而正向迭代器的通用概念不知道如何從任意資料結構中消除資料元素。只有容器成員函式可以消除容器元素,因為只有成員函式知道內部資料結構的詳細資訊。Erase-Remove 慣用法用於從容器中刪除和消除資料元素。

解決方案和示例程式碼

[編輯 | 編輯原始碼]

std::remove 演算法返回一個指向“未使用”元素範圍開頭的迭代器。它不會更改容器的 end() 迭代器,也不會更改容器的大小。erase() 成員函式可用於以下慣用法方式真正從容器中消除成員。

template<typename T>
inline void remove(std::vector<T> & v, const T & item)
{
    // Be careful: if you omit the v.end() parameter to v.erase, the
    // code will compile but only a single item will be removed.
    v.erase(std::remove(v.begin(), v.end(), item), v.end());
}


std::vector<int> v;
// Fill it up somehow
remove(v, 99); // Really remove all elements with value 99

此處 v.end() 的評估順序和 std::remove 的呼叫無關緊要,因為 std::remove 演算法不會以任何方式更改 end() 迭代器。

已知用途

[編輯 | 編輯原始碼]

http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/algorithms/new/remove_erase.html

[編輯 | 編輯原始碼]

參考文獻

[編輯 | 編輯原始碼]

Effective STL,第 32 項 - Scott Meyers

華夏公益教科書