c++ - 从末尾删除 vector 中的所有空元素

标签 c++ string vector

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

我目前的方法(正在进行中)是这样的:

while (Vec.size() > 0 && (Vec.back().size() == 0 || is_whitespace(Vec.back()))
{
    Vec.pop_back();
}

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

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

Input: { "A", "B", " ", "D", "E", " ", "", " " }

Desired Output: { "A", "B", " ", "D", "E" }

最佳答案

由于我第一眼没找到好骗子,这里有一个简单的解决方案:

// 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 由于 this gotcha .

Live example感谢@Killzone Kid .

关于c++ - 从末尾删除 vector 中的所有空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102003/

相关文章:

c++ - 使用 Magick++ 的形态学

c - 以十六进制打印字符串?

c++ - push_back() 后 vector 下标超出范围

c++ - 用于大数组的无复制线程安全环形缓冲区

c++ - 我的链表节点删除功能导致程序的其他部分崩溃

c++ - 是否可以初始化未命名结构的 std::array?

java - 传递输入后丢失字符串中的数据

c++ - 返回语句中 vector 初始化的编译错误

c++ - 如何将文件存储在 char* 中

c# - C# 中的智能 pretty-print 日期时间