c++ - 为什么迭代器指向的数据在从列表中删除后仍保留

标签 c++ list iterator

在这个示例程序中,为什么在列表为空之后,迭代器指向的数据的值仍然保留?
是由于 C++ 中迭代器的实现(即对象的值保存在迭代器中)而必然发生的事情,还是因为内存段被声明为可用,但还没有改变?

#include <iostream>
#include <list>
using namespace std;
int main ()
{
    list<int> mylist;
    list<int>::iterator it = mylist.begin();
    cout << "printing: " << *it << endl;

    mylist.push_back(77);
    mylist.push_back(22);

    // now front equals 77, and back 22

    mylist.front() -= mylist.back();
    it = mylist.begin();
    cout << "printing: " << *it << endl;
    cout << "mylist.front() is now " << mylist.front() << '\n';
    // trying to delete all elements and then see how the iterators are handling it
    it = mylist.begin();
    cout << "printing: " << *it << endl;
    mylist.remove(55);
    cout << "printing: " << *it << endl;
    mylist.remove(22);
    cout << "printing: " << *it << endl;
    cout << "mylist size: " << mylist.size() << endl;
    cout << "mylist.front() is now " << mylist.front() << '\n';
    cout << "printing: " << *it << endl;

    return 0;
}

这是输出:

printing: 495034304
printing: 55
mylist.front() is now 55
printing: 55
printing: 55
printing: 55
mylist size: 0
mylist.front() is now 38375440
printing: 55

最佳答案

Is it something bound to happen due to the implementation of iterators in C++

不,这是未定义的行为。迭代器已失效,无法使用。

is it because the segment of the memory was declared as free for used, but hasn't been changed yet?

是的,这就是为什么你观察到你所观察到的。但是内存可以重新用于其他用途,或者无法访问 - 您不能依赖对未定义行为的任​​何观察。

关于c++ - 为什么迭代器指向的数据在从列表中删除后仍保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21118372/

相关文章:

c++ - 如何从 char * 中删除换行符?

c++ - C:C 中的 volatile 数组

python - 如何使用 Python 将文本文件读入列表或数组

mysql 检查数字是否在逗号分隔的列表中

c++ - 在泛型函数中接受指针/迭代器

C++随机将枚举类型分配给变量

c++ - 多个实例重载函数具有 C 链接

python - 如何使用运算符 'and' 和/或 'or' 映射两个过滤列表

java - 迭代多个 SortedSet 对象

PHP - 迭代两次通用迭代