What is the difference between delete-delete and search-delete

Suppose you want to remove one element from a vector by value. What is the difference between remove -erase:

vector<int> v;
// add some values
vector<int>::iterator it = remove(v.begin(), v.end(), 5);
v.erase(it);

And find-erase

vector<int> v;
// add some values
vector<int>::iterator it = find(v.begin(), v.end(), 5);
if(it != v.end())
{
  v.erase(it);
}
+4
source share
3 answers

Your deletion code is invalid. The remove-erase idiom looks like this:

vector<int>::iterator it = remove(v.begin(), v.end(), 5);
v.erase(it, v.end());

In this case, it has the effect of erasing all values ​​equal to 5, but it minimizes the number of copies needed to achieve this.

Your delete code only deletes the first value, which is 5, so it does what you want.

- , 5, ( std::remove), ( remove). undefined, 5 , remove v.end() .

, , 5, std::remove , 5 . 5 5 , 5s, std::partition std::remove:

auto it = partition(v.begin(), v.end(), [](int i) { return i != 5; });
if (it != v.end()) v.erase(it);

, 5 , , 5, , , :

auto it = partition(v.begin(), v.end(), [](int i) { return i != 5; });
if (it != v.end()) v.pop_back();

- , , 5 ( ), . it != v.end() -, , . v.erase(find(v.begin(), v.end(), 5)).

+13

, , , remove ( ), erase ; vector, .

find .

+1

?

std::remove , all , 5 , . erase, . , :

vector<int>::iterator it = remove(v.begin(), v.end(), 5);
v.erase(it, v.end());

This will delete all items with a value of 5.

In the second example, it std::findfinds the first element of the vector equal to 5, and returns an iterator to it. A call erasewill delete only this item.

That is the difference.

-1
source

All Articles