C++快速排序实现报错求助:数组下标类型无效及函数调用不匹配
Let's work through each of your errors and get your QuickSort working properly:
1. "Invalid types 'double*[double]' for array subscript" (Lines 34 & 36)
This is a simple syntax mix-up in how you're deleting dynamic arrays. You wrote:
delete [smallList]; delete [largeList];
The correct syntax for deleting a dynamic array requires placing the square brackets immediately after delete, not before the array pointer. Your current code makes the compiler think you're trying to use an array subscript on the delete operator (which isn't an array type), hence the error. Fix it to:
delete[] smallList; delete[] largeList;
2. "No matching function for call to Quicksort::QuickSort" (Line 39)
You're trying to call QuickSort(...), but QuickSort is the name of your class—not the member function holding your sorting logic. Your actual sorting code lives in the Processor member function, so you need to call that instead:
// Replace these lines: // QuickSort (smallList,smallList,SmallNum); // QuickSort (largeList,largeList,LargeNum); // With this: Processor(smallList, smallList, SmallNum); Processor(largeList, largeList, LargeNum);
3. Hidden Uninitialized Variable Bug
You declared int SmallNum, LargeNum=0; but never initialized SmallNum to 0. This means SmallNum starts with a random garbage value, which will cause you to write outside the bounds of smallList right away. Fix the declaration to:
int SmallNum = 0, LargeNum = 0;
Corrected Full Code
Here's your code with all fixes applied, plus a couple of extra polish touches:
double *QuickSort::Processor(double *Result, double *Array, int Size) { if (Size == 0) return nullptr; // More idiomatic than returning 0 for C++ pointers double *smallList, *largeList; smallList = new double[Size]; largeList = new double[Size]; double pivot = Array[0]; int SmallNum = 0, LargeNum = 0; // Initialize both counters properly for (int i = 1; i < Size; i++) { if (Array[i] < pivot) smallList[SmallNum++] = Array[i]; else largeList[LargeNum++] = Array[i]; } // Recursively sort the smaller and larger sublists Processor(smallList, smallList, SmallNum); Processor(largeList, largeList, LargeNum); int num = 0; // Don't forget to initialize this counter too! for (int i = 0; i < SmallNum; i++) Result[num++] = smallList[i]; Result[num++] = pivot; for (int i = 0; i < LargeNum; i++) Result[num++] = largeList[i]; // Correct dynamic array deletion syntax delete[] smallList; delete[] largeList; return Result; }
内容的提问来源于stack exchange,提问作者Bryce Purnell

