解除引用列表:: end

问题描述

我在玩std::list。与其他容器类似,std::list::end指std :: list(ref)的past-the-end元素。

因此,我们希望下面的代码可以打印1,2,3,4,5(它会这样做):

std::list<int> l { 1,5 };
for (auto it = l.begin(); it != l.end(); ++it)
{
    std::cout << *it << ",";
}
std::cout << std::endl;

但是,第二个代码段的第二行应该打印5,但是可以做到:

std::cout << *l.begin() << std::endl;
std::cout << *l.end() << std::endl;

输出15

为什么?我正在使用GCC 11和C ++ 11(与C ++ 20 btw相同)。

解决方法

您可以使用-D_GLIBCXX_DEBUG命令行标志查看以调试模式进行构建的原因:

/usr/include/c++/8/debug/safe_iterator.h:270:
Error: attempt to dereference a past-the-end iterator.

Objects involved in the operation:
    iterator "this" @ 0x0x7fff50ac8670 {
      type = __gnu_debug::_Safe_iterator<std::__cxx1998::_List_iterator<int>,std::__debug::list<int,std::allocator<int> > > (mutable iterator);
      state = past-the-end;
      references sequence with type 'std::__debug::list<int,std::allocator<int> >' @ 0x0x7fff50ac85d0
    }
Aborted

与其他容器一样,未定义对end()迭代器的引用。它只是偶然地在非调试模式下工作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...