【问题标题】:When will STL iterator be equal to zero?STL 迭代器什么时候会为零?
【发布时间】:2009-04-02 09:18:47
【问题描述】:

我有一个这样的程序

list<int>:: iterator n = alist.begin();
while(n!= (list<int>::iterator)0)
{
    printf("Element is %d\n",*n);
    n = alist.erase(n);
}

所以我在这里将迭代器与零进行比较。 但在删除最后一个元素后,编译器显示此错误。

*** 检测到 glibc *** ./new: free(): invalid pointer: 0xbf99cb10 *** ======= 回溯:========= /lib/libc.so.6[0xb7d956e1] /lib/libc.so.6(cfree+0x89)[0xb7d96d79] /usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb7f3ff81] ./新[0x8048c81] ./新[0x8048ca6] ./新[0x8048d07] ./新[0x8048d39] ./new(__gxx_personality_v0+0x216)[0x804888e] /lib/libc.so.6(__libc_start_main+0xdc)[0xb7d46f9c] ./new(__gxx_personality_v0+0x49)[0x80486c1] ======= 内存映射:======== 08048000-0804a000 r-xp 00000000 08:09 3704751 /home/sathya/chaithra/archivesthrash/new

如果队列/列表为空,我希望迭代器为零。我应该怎么做? 因为在我的项目中,我只需要将此迭代器与零进行比较,而不是与 alist.end().. 可能的解决方案是什么...?

【问题讨论】:

  • 为什么不能和“alist.end()”比较呢?这似乎是合乎逻辑的事情。

标签: c++ stl iterator


【解决方案1】:

为什么你认为迭代器永远“为零”?迭代器不是指针或索引。如果需要检查容器是否为空,请使用 empty() 成员函数。

【讨论】:

    【解决方案2】:

    改成

    list<int>:: iterator n = alist.begin();
    while(n!= alist.end())
    {
        printf("Element is %d\n",*n);
        n = alist.erase(n);
    }
    

    list<int>:: iterator n = alist.begin();
    while(alist.size() > 0)
    {
        printf("Element is %d\n",*n);
        n = alist.erase(n);
    }
    

    因为您不能将迭代器与 NULL 进行比较 - 这不是迭代器的已定义状态。

    【讨论】:

    • 第二个非常糟糕 - 对于列表,size() 允许为 O(N)。在将 size() 与 0 进行比较的任何地方使用 empty()。
    【解决方案3】:

    也许你想测试一下迭代器的内容是否为0。在这种情况下……你需要改为:

    list<int>::iterator n = alist.begin();
    while( !alist.empty() && 0 != *n) 
    {
        printf("Element is %d\n",*n);
        n = alist.erase(n);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2018-11-07
      • 2013-05-16
      • 2021-12-03
      • 2021-08-19
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多