如何解决解除引用列表:: 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;
输出:1
和5
。
为什么?我正在使用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()
迭代器的引用。它只是偶然地在非调试模式下工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。