使用的未初始化局部变量'Quick'



我正在制作这个函数,它计算交换和比较的总量,这是一个快速排序函数所能完成的总量。然而,当我运行它时,我会得到这个错误:

错误C4700:未初始化的本地变量'quick'使用

这发生在下面函数代码中列出的基本情况的"if"语句中。SwapandComp是我用来跟踪排序的交换和比较的结构的名称,分区是我们找到分离原始数组的位置的函数,也是我们计算交换和比较次数的函数。

int partition(int numbers[], int i, int k) {
int l = 0;
int h = 0;
int midpoint = 0;
int pivot = 0;
int temp = 0;
bool done = false;
// Pick middle element as pivot
midpoint = i + (k - i) / 2;
pivot = numbers[midpoint];
l = i;
h = k;
while (!done) {
// Increment l while numbers[l] < pivot
while (numbers[l] < pivot) {
++l;
totalComps++;
}
// Decrement h while pivot < numbers[h]
while (pivot < numbers[h]) {
--h;
totalComps++;
}
// If there are zero or one elements remaining,
// all numbers are partitioned. Return h
if (l >= h) {
totalComps++;
done = true;
}
else {
// Swap numbers[l] and numbers[h],
// update l and h
temp = numbers[l];
numbers[l] = numbers[h];
numbers[h] = temp;
totalSwaps++;
++l;
--h;
}
}
return h;
}

现在是快速排序函数。如前所述,SwapandComp是我用来跟踪交换和比较的结构。

SwapandComp quicksort(int numbers[], int i, int k) {
SwapandComp quick;
int j = 0;
int z = 0;

// Base case: If there are 1 or zero elements to sort,
// partition is already sorted
if (i >= k) {
return quick;
}
// Partition the data within the array. Value j returned
// from partitioning is location of last element in low partition.
j = partition(numbers, i, k);
// Recursively sort low partition (i to j) and
// high partition (j + 1 to k)
quickSort(numbers, i, j);
quicksort(numbers, j + 1, k);
quick.swaps = totalSwaps;
quick.comps = totalComps;
return quick;
}

在下面的第二行,我写

SwapandComp quick;

用于快速排序结构。这个错误对我来说真的没有意义,因为我确实声明了"quick"作为一个新的结构来返回函数。感谢您的帮助!谢谢

初始化struct如下:

SwapandComp quick = { 0 };
SwapandComp quick;

除非该类型有构造函数,否则在函数中声明带有构造函数的变量将使其处于不确定状态。然后返回它(根据您的基本情况,不首先初始化它(将导致您看到的问题,即"使用未初始化的变量"警告。

可以在声明时初始化成员,例如使用:

SwapandComp quick; quick.swaps = quick.comps = 0;

更好的方法是使用真正的初始化程序,比如:

struct SwapAndComp {
unsigned swaps;
unsigned comps;
SwapAndComp(): swaps(0U) , comps(0U) {};
};

这个方法(初始化是类本身的一部分(允许您正确地创建结构,而的任何用户都不需要担心是否正确。而且,如果你想要灵活性,你可以简单地提供一个允许它的构造函数,同时仍然默认为"设置为零"的情况:

SwapAndComp(unsigned initSwaps = 0U, unsigned initComps = 0U)
: swaps(initSwaps) , comps(initComps) {};

最新更新