简体   繁体   English

从向量中删除最后一个元素直到条件

[英]removing last elements from vector until condition

I ran into a problem where i need to delete the last elements of a vector until a certain condition is met (for sake of this example let it be the element is not zero) 我遇到了一个问题,我需要删除向量的最后一个元素,直到满足特定条件为止(出于这个示例的考虑,让它成为元素不为零)

I wrote this code, it does the trick - 我写了这段代码,可以解决问题-

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

But i would much rather find an stl algorithm that i can use (i can use find_if and then erase, but i'd like to loop once through the elements that i remove...) 但我宁愿发现我可以使用STL算法(我可以使用find_if然后删除,但我想一次循环通过,也就是说,我删除...)

Also, i'm afraid i may be invoking some UB here, should i be worried? 另外,我可能会在这里调用一些UB,我担心吗?

Your code can be simplier: 您的代码可以更简单:

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

Using std::remove or std::remove_if would remove all elements based by criteria, so you should use std::find_if as Vlad provided in his answer. 使用std::removestd::remove_if会根据条件删除所有元素,因此您应按照Vlad在其答案中提供的方式使用std::find_if

Here is an example. 这是一个例子。 It uses the general idiom for erasing vectors 它使用一般习惯来擦除向量

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;
}

The output is 输出是

1 2 3 4 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM