从向量中移除最后的元素,直到条件

removing last elements from vector until condition

本文关键字:条件 元素 最后的 向量      更新时间:2023-10-16

我遇到了一个问题,我需要删除向量的最后一个元素,直到满足某个条件(为了这个例子,假设元素不是零)

我写了这个代码,它做到了技巧-

auto next = vec.rbegin();
while (next != vec.rend())
{
    auto current = next++;
    if (*current == 0)
        vec.pop_back();
    else
        break;
}

但我更愿意找到一个可以使用的stl算法(我可以使用find_if,然后擦除,但我想通过我删除的元素循环一次…)

此外,我担心我可能会在这里调用一些UB,我应该担心吗?

您的代码可以更简单:

while( !vec.empty() && vec.back() == 0 ) 
    vec.pop_back();

使用std::removestd::remove_if将删除所有基于标准的元素,因此您应该使用Vlad在其回答中提供的std::find_if

下面是一个例子。它使用了擦除矢量的通用习惯用法

v.erase( std::remove( /*...*/ ), v.end() )

#include <iostream>
#include <vector>
#include <algorithm>
int main() 
{
    std::vector<int> v = { 1, 2, 3, 4, 5, 0, 0, 0 };
    v.erase( 
        std::find_if( v.rbegin(), v.rend(), 
        []( int x ) { return x != 0; } ).base(), v.end() );
    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;
    return 0;
}

输出为

1 2 3 4 5