【问题标题】:Swap function for a sorting algorithm doesn't work with parameter from the sorting function.排序算法的交换函数不适用于排序函数的参数。
【发布时间】:2017-10-28 10:20:29
【问题描述】:

所以我在另一个头文件上有一个选择排序函数,它采用来自 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;
}

同时,当我不使用函数而只是像这样在循环内编写交换时,(用这段代码替换交换)

int temp = a[i];
a[i] = a[iMin];
a[iMin] = temp;

int temp2 = b[i]
b[i] = b[iMin];
b[iMin] = temp2;

效果很好。

附加信息是我在 source.cpp 中有一个结构,它有两个数组成员作为 a[] 和 b[] 传递,n 只是被排序的数据数。

【问题讨论】:

  • 你的 swap 函数什么都不做。您的问题可以简化为:void f(int x) { x = 42; } int main() { int a = 0; f(a); cout &lt;&lt; a &lt;&lt; "\n"; }
  • 更改交换以使用引用:void swap(int & a, int &b);

标签: c++ algorithm sorting


【解决方案1】:

改变你的交换函数来接受引用,而不是值:

void selection::swap(int& a, int& b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}

当一个函数接受一个值时,对象在传递之前被复制并且在被调用者中不受影响。

【讨论】:

    【解决方案2】:

    在您的程序中,selection::swap() 按值获取参数。由于它应该通过交换它们来修改接收参数的值,因此它应该采用引用:

    void selection::swap(int &a, int &b)
    

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 2017-02-10
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多