簡體   English   中英

為什么我得到:“結束后無法尋找向量迭代器”

[英]why am i getting: “cannot seek vector iterator after end”

所以我正在嘗試使用c++解決約瑟夫斯問題

第一個輸入是人數,第二個是 position 用於殺死下一個人

我收到運行時錯誤:“結束后無法尋找向量迭代器”

代碼:

// josephus.cpp : This file contains the 'main' function. Program execution begins and ends there.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int people = 0, pos = 0;

    cin >> people >> pos;

    vector<int> vp;

    for (int i = 1; i <= people; ++i)
    {
        vp.push_back(i);
    }

    int index = 0;

    while (vp.size() != 1)
    {

        index += pos - 1;

        if (index >= vp.size())
        {
            index -= vp.size();
        }

        vp.erase(vp.begin() + index);
        
    }

    cout << vp[0] << endl;
    return 0;
}

有趣的是輸入數據 10 3 (people = 10, pos = 3) 沒有錯誤。 它給出了正確的答案 4。

但是對於輸入 94 31 (people = 94, pos = 31) 它給了我運行時錯誤。 我認為擦除 function 時會出現問題。

我已經盡我所能。 任何幫助表示贊賞。

正如 1201ProgramAlarm 提到的注釋, index可以大於vp.size() ,這意味着當您嘗試擦除vp.begin() + index時,它將失敗,因為vp.end() - 1之后沒有元素. vp.begin()vp.end()是迭代器,因此當您嘗試在 end ( vp.end() ) 之后尋找迭代器時,它會失敗告訴您這一點。

該程序具有未定義的行為,因為根據序列容器的要求,成員 function erase的參數應是有效的可解引用迭代器。 然而由於這種說法

index += pos - 1;

index的值可以大於或等於表達式2 * ( current size of the vector)

在這種情況下,在下一個 if 語句中

    if (index >= vp.size())
    {
        index -= vp.size();
    }

index將獲得一個大於或等於vp.size()值的值。

結果這個電話

vp.erase(vp.begin() + index);

不會使用有效的可解引用迭代器。

暫無
暫無

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

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