简体   繁体   English

擦除vector中的所有元素,直到第一个非零元素C ++

[英]Erase all elements from vector until first non-zero element C++

I have a vector that will store a variable number of zero elements at its beginning. 我有一个向量,它将在其开头存储可变数量的零元素。 These need to be erased. 这些都需要删除。

I have tried: 我努力了:

while(v.at(0) == 0)
{
    v.erase(v.begin());
}

But this throws out an std::out_of_range error. 但这会抛出std::out_of_range错误。

Any assistance would be appreciated. 任何援助将不胜感激。

You can use std::find_if to find the first non-zero value and then erase those elements: 您可以使用std::find_if查找第一个非零值,然后erase这些元素:

auto first_non_zero = std::find_if(begin(v), end(v), [](int n){ return n != 0; });
v.erase(begin(v), first_non_zero);

( live demo ) 现场演示

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

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