【发布时间】:2015-11-04 13:48:00
【问题描述】:
从 STL 中的集合中删除项目需要一种经常使用的技术,这已成为一种习惯用法:the erase-remove-idiom
此成语最常见的用法之一是从vector<T> 中删除T 类型的项目
std::vector<Widget> widget_collection;
Widget widget;
widget_collection.erase(
std::remove(widget_collection.begin(), widget_collection.end(), widget),
widget_collection.end());
这显然非常冗长,违反了DRY principle - 有问题的向量在那里需要 4 次。
所以我的问题是为什么该标准不提供方便的助手?
类似
widget_collection.erase_remove(widget);
或
std::erase_remove(widget_collection, widget);
这显然可以扩展到
widget_collection.erase_remove_if(widget, pred);
等等……
【问题讨论】:
-
你冷总是自己写。
-
我有! :) 我只是认为这将是对
<algorithm>的一个相当简单的补充,所以所有人都可以从中受益 -
@SteveLorimer 我也有。你擅长
list<>吗? -
@curiousguy 我没有,因为我只使用
list::erase。它当然可以变得更通用。我很高兴N4273被接受,因为它绝对比我的实现更优雅并且覆盖范围更广!
标签: c++ stl c++17 erase-remove-idiom