给定字符串的std::vector
,从末尾开始删除所有空元素(等于空字符串或空格)的最佳方法是什么。当找到非空元素时,元素的删除应该停止。
我目前的方法(正在进行中的工作)如下:
while (Vec.size() > 0 && (Vec.back().size() == 0 || is_whitespace(Vec.back()))
{
Vec.pop_back();
}
其中,is_whitespace
返回一个bool,说明字符串是否为空格。
我怀疑我的方法会在每次迭代时调整向量的大小,这是次优的。也许有了一些算法,就可以在一步之内完成。
输入:{ "A“、"B”、"“、"D”、"E“、”“} 期望输出:{ "A“、"B”、“”、"D“、"E”}
发布于 2018-04-30 06:07:47
由于我乍一看找不到好的欺骗,下面是一个简单的解决方案:
// 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));
注意,由于unsigned
的缘故,lambda中的这个抓到你了。
实例化多亏了@Killzone Kid。
发布于 2018-04-30 06:05:21
这里有一个更好的方法:
for (auto it = Vec.rbegin(); it != Vec.rend() && is_whitespace(*it); )
{
it = Vec.erase(it);
}
它将从结尾开始,并在遇到非空白或到达向量的开头时停止,以第一位为准。注意,我没有在for
循环中增加迭代器。
https://stackoverflow.com/questions/50102003
复制