Element Removal Algorithm

I understand that there is an erase-delete idiom for C ++. And the removeunder method <algorithm>will move the target elements in the back of the range.

However, the result below is confusing to me.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> vec = {10, 20, 30, 20, 30, 20, 10, 10, 20};

    auto pend = remove(vec.begin(), vec.end(), 20);
    cout << "After removing 20: " << endl;
    for (const auto& x : vec) {
        cout << x << " ";
    }
    cout << endl;

    cout << "use pend: " << endl;
    for (auto p = vec.begin(); p != pend; p++) {
        cout << " " << *p;
    }

    cout << endl;
    return 0;
}

Conclusion:

After removing 20:
10 30 30 10 10 20 10 10 20
use pend:
10 30 30 10 10

There are two questions here:

  • For "After removing 20," why are 10 mixed with 20 in the back? 10 30 30 10 10 20 10 10 20

  • For "use pend:" why can't it print the last two more than ten? There are five 10 in the original vector, and 10 should not be deleted?

From the library, the remove () method returns an iterator rollback

ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T & val); , , . , val.

+4
2

:

10 20 30 20 30 20 10 10 20

20, :

10 30 30 10 10

std::remove , unspecified:

, , ,

, :

10 30 30 10 10 xx xx xx xx
               ^
               pend

.

, vec.erase(pend, vec.end()):

, .

+13

++ erase-remove idiom. :

erase-remove ++ , ++.

. C++.

+2

Source: https://habr.com/ru/post/1667970/


All Articles