从末尾删除向量中的所有空元素 [英] Removing all empty elements in a vector from end
问题描述
给定一个 std::vector
字符串,从末尾开始删除所有空元素(等于空字符串或空格)的最佳方法是什么.当发现非空元素时,应停止删除元素.
Given a std::vector
of strings, what is the best way of removing all elements starting from the end that are empty (equal to empty string or whitespace). The removal of elements should stop when a non-empty element is found.
我目前的方法(正在进行中)类似于:
My current method, (work in progress) is something like:
while (Vec.size() > 0 && (Vec.back().size() == 0 || is_whitespace(Vec.back()))
{
Vec.pop_back();
}
其中 is_whitespace
返回一个布尔值,说明字符串是否为空格
where is_whitespace
returns a bool stating if a string is whitespace or not
我怀疑我的方法会在每次迭代时调整向量的大小,这是次优的.也许通过某种算法可以一步完成.
I suspect that my method will resize the vector at each iteration and that is suboptimal. Maybe with some algorithm it is possible to do in one step.
输入:{ "A", "B", " ", "D", "E", " ", "", " " }
Input: { "A", "B", " ", "D", "E", " ", "", " " }
期望输出:{ "A", "B", " ", "D", "E" }
Desired Output: { "A", "B", " ", "D", "E" }
推荐答案
由于乍一看我没有找到好的骗子,这里有一个简单的解决方案:
As I did not find a good dupe on first glance, here is a simple solution:
// 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));
注意 lambda 中的 unsigned
由于这个问题.
Note the unsigned
in the lambda due to this gotcha.
现场示例 感谢 @Killzone Kid.
这篇关于从末尾删除向量中的所有空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!