gpt4 book ai didi

c++ - std::list 中 end() 之后的下一个迭代器

转载 作者:行者123 更新时间:2023-11-27 23:59:26 25 4
gpt4 key购买 nike

#include <iostream>
#include <list>
#include <deque>
int main( void )
{
std::deque< std::deque< int > > integers_lists ;
const std::list< int > list0 { 1 , 2 , 3 } ;
for ( auto current = std::next( list0.cbegin() )
; current != std::next( list0.cend() )
; ++ current ) integers_lists.emplace_back( list0.cbegin() , current ) ;
for ( const auto& sub : integers_lists )
{
for ( auto each : sub ) std::cout << each << " " ;
std::cout << "\n" ;
}
return 0;
}

在这种情况下,STL 是否保证 current != std::next( list0.cend() ) 表达式的正确性?以及 Standard 中具体指出的位置。?

最佳答案

std::next( list0.end() ) 在几乎任何上下文中都是无效的。

即使您将程序简化为:

int main() {
std::list<int> list0 { 1 , 2 , 3 } ;
auto iter = std::next(list0.end());
}

这将是无效的。您可以与 .end() 迭代器进行比较,但您不能取消引用它,也不能通过 std::next 迭代它。这是未定义的行为。

如果你想使用列表中的每个项目一次,只需执行以下操作:

for(auto & reference_to_current : list0) {
/* ... */
}

或者,如果你坚持使用迭代器,

for(auto current =  list0.begin()
; current != list0.end()
; ++ current)
{ /* ... */ }

是的,这将包括所有项目,包括最后一项。 .end() 迭代器很特殊 - 它不指向最后一项,它指向最后一项之后的下一个槽。 “最后一次”。

最后,next(list0.begin()) 跳过第一项。您确定要跳过第一项吗?

更新:如果您确实想跳过第一个项目,但使用所有其他项目,您可以使用

if(list0.empty()) {
/* Error, list must not be empty */
} else {
for(auto current = std::next(list0.begin()) // skip first item
; current != list0.end()
; ++ current)
{ /* ... */ }
}

if 非常重要,因为如果列表为空,我们不能调用 std::next(list0.begin())

关于c++ - std::list 中 end() 之后的下一个迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40328512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com