簡體   English   中英

std :: list中end()之后的下一個迭代器

[英]next iterator after end() in std::list

#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() )表達式的正確性? 以及標准指向的確切位置?

std::next( list0.end() )在幾乎所有上下文中都是無效的。

即使您將程序簡化為:

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

這將是無效的。 您可以與.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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM