2014-09-05 108 views
-1

所以我正在做一个编程任务,并且遇到了一个问题,当我试图将数组传递给头文件时,在编译时收到错误,I我不太清楚如何做到这一点,并非常感谢在传递这些数组时如此的协助。将数组作为参数传递给函数

这里是头文件 “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); 
} 

提前感谢!

+1

在'main()'的函数调用的参数列表中丢失'[]'' – WhozCraig 2014-09-05 08:11:05

+0

不相关的,道具,你实际上正在做通过交换检查进行优化的泡沫排序(你会惊讶多少没有),但是你的泡泡排序会重复排列到数组的最后。 '(交换&& N--){掉期= 0; for(i = 0; i WhozCraig 2014-09-05 08:15:01

+0

由于你的实现是在头文件中,你的函数应该是'inline'来避免多重定义。 (但是在头文件/ cpp中分割声明和定义似乎更好)。 – Jarod42 2014-09-05 09:53:50

回答

3

变化

bubble(Ar[],N); 

bubble(Ar, N); 

(和其他类似的地方为好)

也有在你的代码中的其他问题:

  1. 变长度a rrays也不是C++标准的一部分:

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

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

  2. 这一行产生不确定的行为,因为运营商的参数计算顺序是不确定的:

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

约2:i ++应该明确地为i + 1。在那里和代码中的下一次出现。 – stefaanv 2014-09-05 08:37:20

相关问题