Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove by iterator from std::vector

Tags:

c++

std

vector

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.

like image 909
Narek Avatar asked Feb 05 '15 10:02

Narek


People also ask

How to remove elements from a vector while iterating inside loop?

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

How to erase a vector in C++?

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.

How do you erase an iterator in Python?

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.

How to remove the first element of a vector in Python?

//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.


1 Answers

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).

like image 161
PaulMcKenzie Avatar answered Sep 24 '22 04:09

PaulMcKenzie