2014-09-28 94 views
1

所以我試圖找出一種方法來迭代,雖然數組傳遞到一個函數而不知道大小。我用我的代碼遇到無限循環,因爲數組不是NULL終止。由於數組通過函數變成了指針,我不能使用sizeof(Array)/ sizeof(int)來獲取元素的數量。有沒有什麼辦法沒有NULL終止我的數組?通過函數遍歷c數組

我的查找功能:

int find(const int* arr, int val) 
{ 
    int pos = 0; 
    while (arr != NULL) 
    { 
     if (*arr == val) 
     { 
      return pos; 
     } 
     pos++; 
    } 
    return -1; 
}; 

我的主:

int IntArr[] = { 1, 2, 3, 4, 5 }; 
int index = find(IntArr, 4); 
cout << "find(IntArr, 4)" << endl; 
cout << "index: " << index << endl << endl; 
+1

如果你不知道大小,你是SOL。如果你猜測,你會猜錯。你說沒有終結者?好的,那麼你必須通過其他方式來傳遞長度,就像在另外一個參數中一樣。 – Deduplicator 2014-09-28 18:33:48

+1

傳遞數組的大小,或使用'std :: array'或'std :: vector'並通過引用傳遞,因爲他們知道它們的大小(或者傳遞它們的開始和結束迭代器) – 2014-09-28 18:35:40

+0

PS有'std :: find'函數 – 2014-09-28 18:39:43

回答

1

例如,你可以定義引用接受一個數組的模板功能

template <size_t N> 

int find(const int (& arr)[N], int value) 
{ 
    int pos = 0; 

    while (pos < N && arr[pos] != value) ++pos; 

    return pos == N ? -1 : pos; 
} 

要考慮到在標頭<algorithm>中聲明瞭標準算法std::find。你可以寫例如

#include <algorithm> 
#include <iterator> 

//.. 

int IntArr[] = { 1, 2, 3, 4, 5 }; 
auto ptr = std::find(std::begin(IntArr), std::end(IntArr), 4); 
cout << "find(std::begin(IntArr), std::end(IntArr), 4)" << endl; 
cout << "index: " << std::distance(std::begin(IntArr), ptr) << endl << endl; 
+0

或者只是使用'std :: find'並傳遞兩個迭代器。 – rightfold 2014-09-28 19:04:50