[英]Removing all empty elements in a vector from end
给定一个字符串的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”}
由于我没有在第一眼看到一个好的傻瓜,这是一个简单的解决方案:
// 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
。
这是一个更好的方法:
for (auto it = Vec.rbegin(); it != Vec.rend() && is_whitespace(*it); )
{
it = Vec.erase(it);
}
它将从结束开始并在遇到非空白或到达向量的开始时停止,以先到者为准。 请注意,我没有在for
循环中增加迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.