我的 main.cpp 文件中有问题,程序告诉我 Member reference base type 'int [11]' is not a structure or union
对于我的 QuickSort 行和我的for 循环也是。然后在 cout 行中它说 Adding 'int' to a string does not append to the string and "Use array indexing to silence this warning
.
下面是我遇到问题的 main.cpp 文件。
#include <iostream>
#include "QuickSort.h"
using namespace std;
int main() {
int F[] = {12, 2, 16, 30, 8, 28, 4, 10, 20, 6, 18};
QuickSort(F, 0, F.length-1);
for (int i = 0; i<F.length; i++){
cout << F[i] + " ";
}
return 0;
}
以防万一你需要我的其他密码来破译。 下面是我的 QuickSort.h 文件:
using namespace std;
class QuickSortRecursion{
public:
QuickSortRecursion();
int Partition (int a[], int low, int high);
void QuickSort(int a[], int low, int high);
private:
};
下面是我的 QuickSort.cpp 文件:
QuickSortRecursion::QuickSortRecursion(){
return;
}
int QuickSortRecursion::Partition(int a[], int low, int high){
int pivot = high;
int i = low;
int j = high;
while (i<j){
if (a[i] <= a[pivot]){
i++;
}if (a[i] > a[pivot]){
if ((a[i] > a[pivot]) && (a[j] <= a[pivot])){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
} if (a[j] > a[pivot]){
j--;
}
}
}
int temp = a[i];
a[i] = a[pivot];
a[pivot] = temp;
return i;
}
void QuickSortRecursion::QuickSort(int a[], int low, int high){
if (low >= high){
return;
}
int split = Partition (a, low, high);
QuickSort(a, low, split-1);
QuickSort(a, split+1, high);
}
最佳答案
在
int main() {
int F[] = {12, 2, 16, 30, 8, 28, 4, 10, 20, 6, 18};
QuickSort(F, 0, F.length-1);
for (int i = 0; i<F.length; i++){
cout << F[i] + " ";
}
return 0;
}
F
是一个数组,数组没有任何成员,所以没有 F.length
。
解决方案(按个人喜好排序)
如果可用,请使用 std::size
(C++17 中的新功能)。
int main() {
int F[] = {12, 2, 16, 30, 8, 28, 4, 10, 20, 6, 18};
QuickSort(F, 0, std::size(F)-1);
for (int i = 0; i<std::size(F); i++){
cout << F[i] + " ";
}
return 0;
}
使用 std::vector
而不是原始数组。 std::array 更合适,但我没有好的公式可以制作
std::array<int> F = {12, 2, 16, 30, 8, 28, 4, 10, 20, 6, 18};
^
Need to specify array size here, and if you knew that you there
wouldn't be a problem.
std::vector
示例
int main() {
std::vector<int> F = {12, 2, 16, 30, 8, 28, 4, 10, 20, 6, 18};
QuickSort(F.data(), 0, F.size()-1);
for (int i = 0; i<F.size(); i++){
cout << F[i] + " ";
}
return 0;
}
使用sizeof
获取字节长度然后除以sizeof
一个元素得到数组中元素的个数
int main() {
int F[] = {12, 2, 16, 30, 8, 28, 4, 10, 20, 6, 18};
const int length = sizeof(F) / sizeof(F[0]);
QuickSort(F, 0, length -1);
for (int i = 0; i<length ; i++){
cout << F[i] + " ";
}
return 0;
}
边注
如果您有一个什么都不做的构造函数,让编译器生成它。
如果您有一个没有状态(成员变量)的类,请考虑将其设为命名空间
。
分区看起来不对。看起来你正在尝试 Lomuto Partitioning , 但有点偏离。
关于c++ - 不确定如何修复 "Member reference"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53273326/