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

  • A+
Category:Languages

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.

Any assistance would be appreciated.

 


You can use std::find_if to find the first non-zero value and then erase those elements:

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)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: