我正在使用 erase-remove 习语:
template <typename T>
bool garbageCollectVector(std::vector<T>& v) {
// Use the erase-remove idiom in combination with a lambda expression
v.erase(
std::remove_if(v.begin(), v.end(),
[this](const T& elem) -> bool {
return this->shouldRemove(elem);
}
),
v.end());
return /* what to return? */;
}
并希望返回该方法是否实际删除了任何元素。什么是最干净的方法?
最佳答案
除了大小检查,您还可以拆分您的实现:
template <typename T>
bool garbageCollectVector(std::vector<T>& v) {
// Use the erase-remove idiom in combination with a lambda expression
auto it = std::remove_if(v.begin(), v.end(),
[this](const T& elem) -> bool {
return this->shouldRemove(elem);
});
if (it == v.end()) {
return false;
} else {
v.erase(it, v.end());
return true;
}
}
关于c++ - erase-remove 习语 : did I just delete something?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30749520/