简体   繁体   中英

std::erase in C++

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM