按引用传递 - C++:合并排序 问题:超出范围
pass by reference - C++: Mergesort Issue: going out of scope?
(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的及时回复,指出了我的愚蠢愚蠢。
相关文章:
- 示例代码中使用分隔符将 std::string 拆分为 std::vector 的范围问题
- 命名空间范围问题
- 断言失败错误,C++中的矢量下标超出范围问题
- 指针范围问题和返回类中封装的指针向量内的指针引用
- PlatformIO 的范围问题(?)
- 无法编译 - 范围问题
- 需要帮助将矢量解决范围问题.C
- 来自 gmock 的默认值的范围问题
- 可能的继承范围问题:
- #pragma警告(disable:XXXX)的行为与预期不符(范围问题)
- OpenGL的范围问题
- C++ 引用变量范围问题
- 内存引用范围问题:变量值被重置,如何将值分配给LPCWSTR
- 矢量范围问题
- sed/regex - 更新具有范围问题的源文件
- C++类和范围问题
- C++ 程序未正确执行,可能是范围问题
- 类范围问题的向量
- 如何创建一个通用指针,它可以处理int和double变量并避免范围问题
- 命名空间别名范围问题