假设我有std::unordered_set
个存储类A
的对象。现在我想删除满足给定condition
的对象子集,并将另一个函数应用于子集中的每个对象。这样做的最佳(或优雅)方式是什么?
一种可能的解决方案是:
std::unordered_set<A> myset;
//.. initialize data
std::for_each(myset.begin(), myset.end(), [](A&) { if(condition(A)) { /*do something on A*/} });
auto itrs = std::remove_if(myset.begin(), myset.end(), [](A&) {return condition(A)});
myset.erase(itrs, myset.end());
显然,上述解决方案需要两步函数调用。有什么方法可以简化这个吗?
答案 0 :(得分:4)
首先根据关联容器中的谓词编写要擦除的算法(擦除/删除 - 如果对unordered_set
不起作用):
template <class Container, class Predicate>
void erase_if(Container& c, Predicate pred)
{
using std::begin;
using std::end;
auto first = begin(c);
auto last = end(c);
while (first != last) {
if (pred(*first)) {
first = c.erase(first);
}
else {
++first;
}
}
}
然后传入一个谓词,它既检查你的情况,然后做一些操作:
erase_if(myset, [](A const& a) {
if (condition(a)) {
/* do something */
return true;
}
return false;
});