简体   繁体   English

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

[英]Removing all empty elements in a vector from end

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). 给定一个字符串的std::vector ,从末尾开始删除所有元素的最佳方法是什么(等于空字符串或空格)。 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();
}

where is_whitespace returns a bool stating if a string is whitespace or not 其中is_whitespace返回一个bool,表明字符串是否为空格

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. 也许使用某种算法可以一步完成。

Input: { "A", "B", " ", "D", "E", " ", "", " " } 输入:{“A”,“B”,“”,“D”,“E”,“”,“”,“”}

Desired Output: { "A", "B", " ", "D", "E" } 期望的输出:{“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));

Note the unsigned in the lambda due to this gotcha . 注意由于这个问题 ,lambda中的unsigned

Live example thanks to @Killzone Kid . 活生生的例子感谢@Killzone儿童

Here's a better way: 这是一个更好的方法:

for (auto it = Vec.rbegin(); it != Vec.rend() && is_whitespace(*it); )
{
    it = Vec.erase(it);
}

It will start from the end and stop once non-whitespace has been encountered or the beginning of the vector is reached, whichever comes first. 它将从结束开始并在遇到非空白或到达向量的开始时停止,以先到者为准。 Note that I don't increment the iterator in the for loop. 请注意,我没有在for循环中增加迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM