使用的XCode 4.6测试在Mac OS X上。
此示例代码显示移除的最后一个元素std::list
的作品如我所料:一个迭代参考list::end()
仍然是“1过去的结束”,并仍然有效, 甚至可以通过删除最后一个元素 。
但是第二个例子反驳我的直觉。 删除列表中的第一个元素改变list::rend()
我认为是“1过去的开始。”
当时我的意料错了吗? 为什么是错的? 为什么通过最后一个元素的缺失确实你提到的“1过去的结束”仍然有效(它不应该?),但一提到“1在开始前( .rend()
去除前的后变为无效元件?
void printList( list<int>& os )
{
for( int& i : os )
printf( "%d ", i ) ;
puts("");
}
void testList()
{
list< int > os ;
os.push_back( 1 ) ;
os.push_back( 2 ) ;
os.push_back( 3 ) ;
os.push_back( 4 ) ;
os.push_back( 5 ) ;
// Forward iterators: reference to .end() not invalidated when remove last elt.
list<int>::iterator fwdEnd = os.end() ;
printList( os ) ;
os.erase( --os.end() ) ; // remove the 5 (last elt)
printList( os ) ;
if( fwdEnd == os.end() ) puts( "YES, fwdEnd==os.end() still, iterators not invalidated" ) ; // I get __this__ result
else puts( "NO: fwdEnd INVALIDATED" ) ;
list<int>::reverse_iterator revEnd = os.rend() ;
// remove the front element
printList( os ) ;
os.erase( os.begin() ) ; // removes the 1
printList( os ) ;
if( revEnd == os.rend() ) puts( "YES revEnd is still valid" ) ;
else puts( "NO: revEnd NOT valid" ) ; // I get __this__ result
}