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.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.
If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the vector::erase approach would move all of the elements from the position to the end multiple times.
Get the vector and the element to be deleted Initialize a reverse iterator on the vector Erase the required element with the help of base () and erase () Reason for using base (): erase () returns a valid iterator to the new location of the element which follows the one, which was just erased, in a forward sense.
What happens is that remove compacts the elements that differ from the value to be removed ( number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements (whose value is unspecified). Show activity on this post.
//Now the vector (v) has 2 elements in it, with size 2 v.pop_front(); // This method will remove the first element for(int i=0;i<v.size();i++){ cout << v[i] << " "; } //Prints [1] return 0; } Removes either a single element or a range of elements.
What happens is that remove compacts the elements that differ from the value to be removed ( number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements (whose value is unspecified). std::remove () shifts elements such that the elements to remove are overwritten.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With