簡體   English   中英

在C ++中列出迭代器不可遞增的錯誤消息

[英]List iterator not incrementable error message in C++

作為一個新手,我正在嘗試使用list-class在C ++中實現排序功能。 但是,運行代碼我得到的錯誤是列表迭代器不可遞增...但是它似乎不太可能,因為它應該是可遞增的!

碼:

void shuffle (list<int> &list1)
{
    list<int> smaller;
    list<int> larger;

    if (list1.size() > 1)
    {
        list<int>::iterator it;
        //int it;

        int x = list1.front();


        for (it = list1.begin(); it != list1.end(); it++)
        {                                       
            if(*it <= x)
            {
                smaller.push_front(*it);
                list1.pop_front();

            }
            else
            {
                larger.push_back(*it);
                list1.pop_front();
            }
            shuffle (smaller);
            shuffle (larger);
        }
    }
    else
    {
        print(smaller);
        print(larger);

        //cout << "No sorting needed! The list still looks like: ";
        //print(list1);
    }
    print(smaller);     
    print(larger);
}

我在de CPP文件中主要實現了這個功能。

有人有什么建議嗎?

您對list1.pop_front()的調用將刪除迭代器最初指向的元素,使其無效。 無效的迭代器無法遞增。 :)

用調試器找了幾分鍾。 當你逐步完成程序時,請注意'它'的價值。 我不知道你是否知道如何使用調試器,但如果沒有,請自己幫忙並學習它。 這是一個非常寶貴的工具。

(順便說一句,將來,請明確說明錯誤是在編譯時還是在運行程序時發生的。你的問題說明了“編譯程序”時發生的錯誤。我剛剛為你編輯了這個問題,希望你不介意。但這是一個重要的區別,並且更難以准確地回答你的問題)

在我注釋掉print()的調用並在開頭添加了以下內容后,我還能夠使用VS2008編譯發布的代碼:

#include <list>
using namespace std;

這是我的主要內容:

> int _tmain(int argc, _TCHAR* argv[])
{
//DEFINE LIST
list <int> list1;
//FILL LIST
list1.push_front(5);
list1.push_front(2);
list1.push_front(1);
list1.push_front(9);
list1.push_front(12);
list1.push_front(3);
list1.push_front(4);
//PRINT LIST BEFORE SORTING
print(list1);
//SORT LIST

shuffle(list1);



//PRINT AFTER SORTING

system("pause");




return 0;

並且錯誤消息只有1,即如果我調試它(​​在VC ++ 2008中按F5)我得到一個彈出窗口,列表迭代器不可遞增

暫無
暫無

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

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