(原創) array傳進function該怎麼寫才好? (C/C++) (C)

由於C/C++不像C#可直接從array身上取得array size,導致C/C++ developer須自己處理array size,以下是常見的幾種寫法。

1.在陣列尾端放一個特別的marker代表結束。C-Style string就是用這種技巧,如以下寫法。

 1#include <iostream>
 2
 3using namespace std;
 4
 5void func(char *pia) {
 6  while(*pia) {
 7    cout << *pia++ << endl;
 8  }

 9}

10
11int main() {
12  char ia[] = {'a''b''c''\0'};
13  func(ia);
14}


2.將陣列第一個元素和最後一個元素傳進去,STL的algorithm就是使用這個技巧,如sort(svec.begin(), svec.end());

 1/* 
 2(C) OOMusou 2007 http://oomusou.cnblogs.com
 3
 4Filename    : ArrayPassToFunctionSTL.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to use pass array to function by STL convention
 7Release     : 01/03/2007 1.0
 8*/

 9
10#include <iostream>
11
12using namespace std;
13
14void func(const int *beg, const int *end) {
15  while(beg != end) {
16    cout << *beg++ << endl;
17  }

18}

19
20int main() {
21  int ia[] = {012};
22  func(ia, ia + 3);
23}


3.傳統C語言的做法,將array size當成參數傳進去

 1/* 
 2(C) OOMusou 2007 http://oomusou.cnblogs.com
 3
 4Filename    : ArrayPassToFunctionCStyle.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to use pass array to function by C Style
 7Release     : 01/03/2007 1.0
 8*/

 9#include <iostream>
10
11using namespace std;
12
13void func(int *pia, size_t arr_size) {
14  for(size_t i = 0; i != arr_size; ++i) {
15    cout << pia[i] << endl;
16  }

17}

18
19int main() {
20  int ia[] = {012};
21  func(ia, 3);
22}


4.使用function template + refference array
請參考(原創) 如何使用function template傳遞array? (C/C++) (template)

5.使用boost::array
請參考(原創) 如何使用boost::array? (C/C++) (boost)

See Also
(原創) 如何使用function template傳遞array? (C/C++) (template)
(原創) array傳進function該怎麼寫才好? (.NET) (C#)
(原創) 如何使用boost::array? (C/C++) (boost)

Reference
C++ Primer 4th P.242

posted on 2007-02-09 21:14  真 OO无双  阅读(37381)  评论(0编辑  收藏  举报

导航