繁体   English   中英

C ++:Mergesort问题:超出范围?

[英]C++: Mergesort Issue: going out of scope?

(C ++)大家好,这是我第一次尝试进行mergesort。 我看到的代码类似于发布了先前问题的人: 此处 在较低级别,排序按预期进行。 但是,我相信我的问题是排序的数组在每个较低级别之后都超出范围,因此永远不会正确排序。 在这种情况下,我尝试使用“ std :: vector&”通过引用传递。 我错了吗? 通过引用传递的正确方法是什么?

下面是我的代码:

/*
MERGE SORT
breaking down the sorting into pairs concursively until we are comparing only two values
The two integers parameters denotes indices for beginning and ending values in vector
Merge sort inclusive of both left and right range
*/
#include <vector> // for using vectors in c++
void merge(std::vector<int>& inputv, int beg_i, int end_i)
{
    int d = beg_i;  // used as an index
    int e = beg_i + (end_i - beg_i)/2 + 1;  // used as an index

    int y = beg_i + (end_i - beg_i)/2;     // used as a check against d
    int z = end_i;  // used as a check against e

    std::vector<int> tempvect(inputv.size());

    for (int c = beg_i; c < z+1; c++)
    {
        if (e > z && d > y)
        {
            // do nothing
        }
        else if (e > z)
        {
            tempvect[c] = inputv[d];
            d++;
        }
        else if (d > y)
        {
            tempvect[c] = inputv[e];
            e++;
        }

        else if(inputv[d] > inputv[e])
        {
            tempvect[c] = inputv[e];
            e++;
        }
        else if(inputv[d] <= inputv[e])
        {
            tempvect[c] = inputv[d];
            d++;
        }
    }
    for (int i = beg_i; i < end_i+1; i++)
    {
        inputv[i] = tempvect[i];
    }
}

void mergesort(std::vector<int> inputvector, int beg_i, int end_i)
{
    if(end_i - beg_i == 0) 
    {
        // do nothing
    }
    if(end_i - beg_i >= 1)
    {
        int mid_i = beg_i + (end_i - beg_i)/2;

        mergesort(inputvector,beg_i,mid_i); // reclusive to last card
        mergesort(inputvector,mid_i+1,end_i);   // resulsive to last card
        merge(inputvector,beg_i,end_i); // actual implementation to sort and merge the vectors
    }

}

如果要模仿在突出显示的线程中看到的代码,请注意该代码使用指针。 使用指针的函数基本上是在更改指针所指向的内容。

因此,您应该这样做以模拟此行为:

void mergesort(std::vector<int>& inputvector, int beg_i, int end_i)

您必须通过参考传递矢量。 之所以看不到结果,是因为按值传递会创建本地临时副本,并且当函数返回时,该临时副本就会消失。 您不需要这样做-您希望将结果定向到要传递的向量,而不是临时副本,因此请按引用传递向量。

无论如何,我意识到它仍然超出范围的原因是尽管我这样做:

void merge(std::vector<int>& inputv, int beg_i, int end_i)

我没有这样做:

void mergesort(std::vector<int>& inputvector, int beg_i, int end_i)

感谢PaulMcKenzie的及时答复,指出了我愚蠢的愚蠢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM