For removing an iterator from std::vector
I can do these two things:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
Or I can do this:
auto it = find(vec.begin(), vec.end(), number_in);
vec.erase(it);
The second is more intuitive, I guess, but which one is faster?
EDIT: Elements in vector are unique and we don't have to worry to delete several elements at once.
This post will discuss how to remove elements from a vector while iterating inside a loop in C++... The idea is to use iterators to iterate the vector and call the `vector::erase` function if the current element matches the predicate. TECHIE DELIGHT </> Ace your Coding Interview FAANG Interview PrepPractice Hot Data Structures and Algorithms
vector::erase () 1. Run a loop till the size of the vector. 2. Check if the element at each position is divisible by 2, if yes, remove the element and decrement iterator. 3. Print the final vector.
We can do that in many ways: 1 Use the return value of erase () for setting the iterator to the next element. ... 2 Decrement the iterator after it is passed to the erase () but before erase () is executed. ... 3 Call erase () on a duplicate of the original iterator after advancing the original iterator to the next element.
//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.
The first one is guaranteed to work correctly, while your second version may be faster (due to std::find
stopping at the first item that matches), but it certainly is not safer.
auto it = find(vec.begin(), vec.end(), number_in);
if (it != vec.end())
vec.erase(it);
That would ensure you are not erasing an invalid iterator.
So it depends on your needs. If you want a program that is correct, the first one works without further intervention, however the second requires a bug ticket from your customer and then you have to go fix it (as above).
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