擦除 - 删除成语:我刚刚删除了什么?

Phi*_*Lab 0 c++ std stdvector

我正在使用擦除删除成语:

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? */;
}
Run Code Online (Sandbox Code Playgroud)

并且想要返回该方法是否实际删除了任何元素.什么是干净办呀?

Jar*_*d42 5

除尺寸检查外,您可以拆分实施:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)