所以我在另一个头文件中有一个选择排序函数,它接受来自source.cpp的数组参数 这应该对数组进行排序,但是当我使用交换函数时它不起作用。
class selection
{
public:
void selectionSort(int a[],int b[], int n);
void swap(int a, int b);
};
void selection::selectionSort(int a[], int b[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int iMin = i;
for (int j = i + 1; j < n; j++)
{
if (a[j] < a[iMin])
iMin = j;
}
swap(a[i], a[iMin]);
swap(b[i], b[iMin]);
}
for (int i = 0; i < n; i++)
{
cout << a[i] << ' ';
cout << b[i] << endl;
}
cout << endl;
}
void selection::swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
同时,当我不使用函数而只是简单地在循环中写入交换时,(用此代码替换swap)
int temp = a[i];
a[i] = a[iMin];
a[iMin] = temp;
int temp2 = b[i]
b[i] = b[iMin];
b[iMin] = temp2;
效果很好。
附加信息是我在source.cpp中有一个结构,它有两个数组成员,它们作为[]和b []传递,n只是被排序的数据的数量。
答案 0 :(得分:2)
更改交换功能以接受引用,而不是值:
void selection::swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
当一个函数接受一个值时,该对象在传递之前被复制,并且在被调用者中不受影响。
答案 1 :(得分:0)
在你的程序中,selection::swap()
按值获取参数。由于它应该通过交换来修改接收参数的值,因此应该使用引用:
void selection::swap(int &a, int &b)