c++ std::vector 使用Erase–remove idiom删除特定的value

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 to erase.

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> 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值