wiki: Erase–remove idiom
一般删除vector中的某个值,需要遍历整个vector找到该值的下标再erase.
采用erase-remove方式可以避免多次后续元素前移
These algorithms do not remove elements from the container, but move all elements that don't fit the removal criteria to the front of the range, keeping the relative order of the elements. This is done in a single pass through the data range.
As no elements are actually removed and the container retains the same size, the tail of the array has a length equal to the number of "removed" items; these items remain in memory but in an unspecified state.
remove
returns an iterator pointing to the first of these tail elements so that they can be deleted using a single call toerase
.
remove 后vector大小不变,返回末尾元素的iterator,因此需要erase掉末尾元素到vector.end()之间的空间,避免内存泄漏。
例子:
#include <algorithm> // remove and remove_if
int main() {
// Initializes a vector that holds numbers from 0-9.
std::vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Print(v);
// Removes all elements with the value 5.
v.erase(std::remove(v.begin(), v.end(), 5), v.end());
Print(v);
}
输出:
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 6 7 8 9
最后,记得 #include <algorithm>