2014-09-05 111 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

相關問題