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