2011-01-30 63 views
1

我想發送一個數組到一個函數!函數中的C++數組

我是一個PHP程序員,所以我用PHP編寫的例子,並請其轉換爲C++:

function a($x) { 
    foreach ($x as $w) print $w; 
} 

$test = array(1, 2, 3); 
a($test); 

回答

11

要做到這一點,最好的辦法是讓功能拍攝一對迭代:一個範圍的開始和一個範圍的結束(這是真正的「一個過去的結束」的範圍):

template <typename ForwardIterator> 
void f(ForwardIterator first, ForwardIterator last) 
{ 
    for (ForwardIterator it(first); it != last; ++it) 
     std::cout << *it; 
} 

,那麼你可以調用這個函數與任何範圍,無論該範圍來自數組或字符串或任何其他類型的序列:

// You can use raw, C-style arrays: 
int x[3] = { 1, 2, 3 }; 
f(x, x + 3); 

// Or, you can use any of the sequence containers: 
std::array<int, 3> v = { 1, 2, 3 }; 
f(v.begin(). v.end()); 

欲瞭解更多信息,請考慮讓自己a good introductory C++ book

+1

+1:特別是對於最後一句話。如果通過實驗進行探索,C++可能會變成一場噩夢。你確定鏈接是正確的嗎?它指向boost :: bind。 – 6502 2011-01-30 21:20:29

+0

@ 6502:糟糕!感謝您的提醒。複製粘貼失敗。 – 2011-01-30 21:21:45

2

嘗試此方法:

int a[3]; 
a[0]=1; 
a[1]=... 

void func(int* a) 
{ 
    for(int i=0;i<3;++i) 
     printf("%d",a++); 
} 
1
template <typename T, size_t N> 
void functionWithArray(T (&array)[N]) 
{ 
    for (int i = 0; i < N; ++i) 
    { 
     // ... 
    } 
} 

void functionWithArray(T* array, size_t size) 
{ 
    for (int i = 0; i < size; ++i) 
    { 
     // ... 
    } 
} 

第一個使用的實際陣列和陣列的長度並不需要,因爲其在編譯已知指定時間。第二個指向一塊內存,所以需要指定大小。

這些功能可以通過兩種不同的方式使用:

int x[] = {1, 2, 3}; 
functionWithArray(x); 

和:

int* x = new int[3]; 
x[0] = 1; 
x[1] = 2; 
x[2] = 3; 
functionWithArray(x, 3);