簡體   English   中英

從末尾刪除向量中的所有空元素

[英]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

活生生的例子感謝@Killzone兒童

這是一個更好的方法:

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

它將從結束開始並在遇到非空白或到達向量的開始時停止,以先到者為准。 請注意,我沒有在for循環中增加迭代器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM