-1

I am confused about function of std::erase in C++.

The following code gets the same output before and after std::erase is called.But if iterate through the list after performing std::erase then in output the erased value is not showing. Help me understand std::erase.

#include<bits/stdc++.h>
using namespace std;

int main()
{
    list<int> v;
    v.push_back(12);
    v.push_back(10);
    v.push_back(20);

    list<int>::iterator it;
    it = v.begin();
    printf("%u %d\n", it, *it);
    v.erase(it);
    printf("%u %d\n", it, *it);

    for(it= v.begin(); it!= v.end(); it++)
        cout<< *it<<" ";
    return 0;
}

Output:

"Memory address" 12  
"Memory Address" 12  
10 20
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

9

erase invalidates the iterator you give it (plus potentially other ones, depending on the container).
Using and dereferencing this iterator afterwards is undefined behaviour.

Quentin
  • 62,093
  • 7
  • 131
  • 191
2

According to the C++ Standard relative to the class template list

Effects: Invalidates only the iterators and references to the erased elements.

Thus the program has undefined behavior.

After this statement

v.erase(it);

the iterator it that initially was set as

it = v.begin();

now does not correspond to v.begin() and the output of the loop

for(it= v.begin(); it!= v.end(); it++)
    ^^^^^^^^^^^^^         
    cout<< *it<<" ";

confirms that.

Instead of

v.erase(it);

you could write

it = v.erase(it);

and in this case the returned iterator will indeed correspond to the iterator returned by v.begin()

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335