从末尾删除向量中的所有空元素

Stu*_*urm 3 c++ string vector

给定一个std::vector字符串,删除从末尾开始的所有空元素(等于空字符串或空格)的最佳方法是什么。当发现非空元素时,应停止删除元素。

我当前的方法(正在进行中)类似于:

while (Vec.size() > 0 && (Vec.back().size() == 0 || is_whitespace(Vec.back()))
{
    Vec.pop_back();
}
Run Code Online (Sandbox Code Playgroud)

whereis_whitespace返回一个 bool 值,说明字符串是否为空格

我怀疑我的方法会在每次迭代时调整向量的大小,这是次优的。也许通过某种算法可以一步完成。

输入:{ "A", "B", " ", "D", "E", " ", "", " " }

所需输出:{“A”,“B”,“”,“D”,“E”}

Bau*_*gen 5

由于我乍一看并没有找到一个好的骗局,这里有一个简单的解决方案:

// Helper function to see if string is all whitespace
// Can also be implemented as free-function for readablity and
// reusability of course
auto stringIsWhitespace = [](const auto &str)
{
    return std::all_of(
        begin(str), end(str), [](unsigned char c) { return std::isspace(c); });
};

// Find first non-whitespace string from the back
auto it = std::find_if_not(rbegin(Vec), rend(Vec), stringIsWhitespace);
// Erase from there to the end
Vec.erase(it.base(), end(Vec));
Run Code Online (Sandbox Code Playgroud)

unsigned由于这个问题,请注意lambda 中的。

感谢@Killzone Kid的生动示例