按引用传递 - C++:合并排序 问题:超出范围

pass by reference - C++: Mergesort Issue: going out of scope?

本文关键字:范围 问题 合并 C++ 按引用传递 排序      更新时间:2023-10-16

(C++)大家好,这是我第一次尝试合并排序。我看到我的代码类似于之前发布过问题的人:这里。在较低级别,排序按预期工作。但是,我相信我在这里的问题是排序数组在每个较低级别之后都超出了范围,因此从未正确排序。在这种情况下,我尝试使用"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的及时回复,指出了我的愚蠢愚蠢。