簡體   English   中英

std :: list.end()不返回“ past-the-end”迭代器

[英]std::list.end() is not returning “past-the-end” iterator

我最近開始學習C ++迭代器和指針,在搞一些基本練習的同時,遇到了一種我認為確實很不正常的情況。

#include <iostream>
#include <vector>
#include <time.h>
#include <list>
#include <array>

using namespace std;

template<typename ITER>

void print_with_hyphens(ITER begin, ITER end){
    cout << "End: " << *(end) << endl;
    cout << "Begin: " << *begin << endl;

    for(ITER it = begin; it != end; it++){
       cout << *it << endl;
    }

    cout << endl << "Finished" << endl;

}

int main()
{
    vector<int> v { 1, 2, 3, 4, 5};
    list<int> l { 1, 2, 3, 4, 5};

    print_with_hyphens(v.begin(), v.end());
    print_with_hyphens(l.begin(), l.end());
//    print_with_hyphens(a.begin(), a.end());


    return 0;
}

當我像這樣運行它時,會得到以下異常結果:

代碼結果

現在,向量正在返回一個奇怪的(如果我沒有記錯的話,是隨機的)值,因為它試圖訪問一個不存在的值,因此“過去了”迭代器。 對於列表,它應該是相同的,但是,列表返回值5。它是否還應該返回“過去了”迭代器?

取消引用無效的迭代器或訪問越界數組索引之類的事情都會產生未定義的行為

這意味着C ++標准未指定執行該操作時應發生的情況。 可能會發生任何事情,例如分段錯誤或獲取隨機值,這取決於標准庫實現和編譯器之類的情況。

不用說,程序不應依賴未定義的行為。

在本文中,短語“過去”是抽象的。 這意味着迭代器不在容器中元素的邏輯順序的末尾。 並不意味着有位於只是在內存中的容器,你可以訪問和讀取數據后的一些文字位。

因為它是“ past-the-end”,並且不引用任何實際元素,所以不允許取消引用end迭代器。 這樣,您會得到怪異的行為。

暫無
暫無

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

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