なぜマージソートで範囲外のエラーをベクトル添え字を取得するのですか?

StackOverflow https://stackoverflow.com/questions/3563173

質問

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);
}

このコードの問題は何ですか? Vector subscript out Out range Errorを取得しています。

役に立ちましたか?

解決

サブベクトルは誤って指定されています。
イテレーターは、終わりを過ぎてから始まりを指定していることを忘れないでください。

したがって、これはベクトルの中央要素と最後の要素を逃します。
また、長さ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パラメーターであるため、参照によって渡す必要があります。ただし、最初と2番目のパラメーターは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);  

他のヒント

SZ == 2の場合、 &a[(sz/2)+1] 2]のアドレスを取得しようとします。これにより、このエラーが発生します。

マーティンは正しいです、問題は補助ベクトルのcontructorです。

元のベクトル:1 9 7 9 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

そして、Merge-Sortやその他のソートアルゴリズムについて話して、私は非常に便利なWebを見つけました:

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top