簡體   English   中英

為什么在合並排序中出現矢量下標超出范圍錯誤?

[英]Why am I getting vector subscript out of range error in the Merge Sort?

void merge(vector<int> dst,vector<int> first,vector<int> second)
{
    int i=0,j=0;

    while(i<first.size()&&j<second.size())
    {
        if(first[i]<second[j])
        {
            dst.push_back(first[i]);
            i++;
        }
        else
        {
            dst.push_back(second[j]);
            j++;
        }
    }
    while(i<first.size()
    dst.push_back(first[i++]);

    while(j<second.size())
    dst.push_back(second[j++]);
}

void mergeSort(vector<int> &a)
{   
    size_t sz = a.size();
    cin.get();
    if(sz>1)
    {   
        vector<int> first(&a[0],&a[sz/2]);
        vector<int> second(&a[(sz/2)+1],&a[sz-1]);

        mergeSort(first);
        mergeSort(second);

        merge(a,first,second);  
    }
}

void MergeSort(int* a,size_t size)
{
   vector<int> s(&a[0],&a[size-1]);
   mergeSort(s);
}

有人可以幫我這段代碼有什么問題嗎? 我收到向量下標超出范圍錯誤。

如果sz == 2, &a[(sz/2)+1]將嘗試獲取a [2]的地址,這將給您此錯誤。

您的子向量指定不正確。
請記住,迭代器將開始指定為結束之后的開始。

因此,這將丟失向量中的中間元素和最后一個元素。
對於長度為2的真正短向量也未定義

    vector<int> first(&a[0],&a[sz/2]);
    vector<int> second(&a[(sz/2)+1],&a[sz-1]);

假設a是向量{A,B,C,D}

    first:  {A,B}   0 -> 2 (where 2 is one past the end so index 0 and 1_
    second: {}      3 -> 3 (Since one past the end equals the start it is empty}

或嘗試更大的向量:{A,B,C,D,E,F,G,H,I}

    first:  {A, B, C, D}    0 -> 4 (4 is one past the end so index 0,1,2,3)
    second: {F, G, H}       5 -> 8 (8 is one past the end so index 5,6,7)

或嘗試使用較小的向量:{A,B}

    first:  {A}    0 -> 1
    second: {BANG} 2 -> 1

應該:

    int* st = &a[0];
    // Using pointer arithmatic because it was too late at night
    // to work out if &a[sz] is actually legal or not.
    vector<int> first (st,      st+sz/2]); // sz/2 Is one past the end.
    vector<int> second(st+sz/2, st+sz   ); // First element is sz/2  
                                           // one past the end is sz

向量傳遞到merge()中。 dst參數是out參數,因此必須通過引用傳遞。 但也請注意,第一個和第二個參數是const,因此我們可以通過const引用進行傳遞(以避免復制步驟)。

void merge(vector<int>& dst,vector<int> const& first,vector<int> const& second)

還有合並功能:

將值推入dst。 但是dst已經從輸入的數據中充滿了。因此,在執行合並之前,必須清除目標。

    mergeSort(first);
    mergeSort(second);

    // Must clear a before we start pushing stuff into.
    a.clear();   // Add this line.
    merge(a,first,second);  

Martin是對的,問題出在輔助向量的構造函數上:

原始向量:1 9 7 9 2 2 7 2 1 9 8

iter1:2,iter2:8

   vector<int> v( iter1, iter2 ); //new vector: 2 7 2 1 9

http://www.cppreference.com/wiki/stl/vector/vector_constructors

在談論合並排序和其他排序算法時,我發現了一個非常有用的網站:

http://www.sorting-algorithms.com/merge-sort

暫無
暫無

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

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