繁体   English   中英

将数组作为参数传递给函数

[英]Passing an array as a parameter to a function

因此,我正在进行编程任务,但遇到一个问题,当我每次尝试将数组传递到头文件时,在编译时都会收到错误消息,我不太清楚如何执行此操作,并且会非常感谢您在传递这些数组方面的帮助。

这是头文件“ sorting.h”

#include <iostream>
#include <cstdlib>

using namespace std;

int cost = 0;

void bubble(int Ar[],int N)
{
  cost=0;
  int swaps = 1;
  while(swaps)
  {
    swaps=0;
    for(int i = 0;i<N;i++)
    {
      if(Ar[i]>Ar[i++])
      {
        swap(Ar[i],Ar[i++]);
        swaps = 1;
        cost += 6;
      }
      cost++;
    }
  }
  for(int i=0;i<N;i++)
  {
    cout<<Ar[i]<<endl;
  }
  cout<<cost<<endl;
}

void shellSort(int Ar[], int N)
{
  cost=0;
  int swaps = 1;
  int gap = N/2;
  while(gap>0)
  {
    while(swaps)
    {
      swaps = 0;
      for(int i = 0;i<N;i++)
      {
        if(Ar[i]>Ar[i+gap])
        {
          swap(Ar[i],Ar[i+gap]);
          swaps = 1;
          cost+=6;
        }
        cost++;
      }
    }
    gap=gap/2;
  }
  for(int i = 0;i<N;i++)
  {
    cout<<Ar[i]<<endl;
  }
  cout<<cost<<endl;
}


void quickSort(int Ar[],int left, int right, int N)
{
  cost = 0;
  int i=left,j=right,tmp;
  int pivot = Ar[(left+right)/2];
  /*partition*/
  while(i<=j)
  {
    while(Ar[i]<pivot)i++;
    while(Ar[j]>pivot)j--;
    if(i<=j)
    {
      tmp=Ar[i];
      Ar[i]=Ar[j];
      Ar[j]=tmp;
      i++;
      j--;
      cost +=6;
    }
    cost+=1;
  }
  /* recursion*/
  if(left<j)quickSort(Ar,left,j,N);
  if(i<right)quickSort(Ar,i,right,N);
  for(int i=0;i<N;i++)
  {
    cout<<Ar[i]<<endl;
  }
  cout<<cost<<endl;
}

/*#if _INCLUDE_LEVEL__<1
int main()
{

}
#endif*/

这是主文件“ sorting2.cpp”

#include <iostream>
#include <cstdlib>
#include "sorting.h"

using namespace std;

//void bubble();
//void shellSort();
//void quickSort();

int main()
{
  int N = 20;
  int Ar[N];
  int Ar2[N];

  for(int i = 0;i<N;i++)
  {
    Ar[i] = Ar2[i] = rand()%100;
  }

  bubble(Ar[],N);

  for(int i = 0;i<N;i++)
  {
    Ar[i] = Ar2[i];
  }

  shellSort(Ar[],N);

  for(int i = 0;i<N;i++)
  {
    Ar[i] = Ar2[i];
  }

  quickSort(Ar[],0,19,N);
}

提前致谢!

更改

 bubble(Ar[],N);

 bubble(Ar, N);

(以及其他类似的地方)

您的代码中还有其他问题:

  1. 可变长度数组不属于C ++标准:

     int Ar[N]; int Ar2[N]; 

    你应该改变int N = 20; const int N = 20;

  2. 由于未指定运算符参数的评估顺序,因此此行会产生未定义的行为:

     if(Ar[i]>Ar[i++]) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM