(原創) 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
3
using namespace std;
4
5
void func(char *pia) {
6
while(*pia) {
7
cout << *pia++ << endl;
8
}
9
}
10
11
int main() {
12
char ia[] = {'a', 'b', 'c', '\0'};
13
func(ia);
14
}

2

3

4

5

6

7

8

9

10

11

12

13

14

2.將陣列第一個元素和最後一個元素傳進去,STL的algorithm就是使用這個技巧,如sort(svec.begin(), svec.end());
1
/*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : ArrayPassToFunctionSTL.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to use pass array to function by STL convention
7
Release : 01/03/2007 1.0
8
*/
9
10
#include <iostream>
11
12
using namespace std;
13
14
void func(const int *beg, const int *end) {
15
while(beg != end) {
16
cout << *beg++ << endl;
17
}
18
}
19
20
int main() {
21
int ia[] = {0, 1, 2};
22
func(ia, ia + 3);
23
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

3.傳統C語言的做法,將array size當成參數傳進去
1
/*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : ArrayPassToFunctionCStyle.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to use pass array to function by C Style
7
Release : 01/03/2007 1.0
8
*/
9
#include <iostream>
10
11
using namespace std;
12
13
void 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
19
int main() {
20
int ia[] = {0, 1, 2};
21
func(ia, 3);
22
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

4.使用function template + refference array
請參考(原創) 如何使用function template傳遞array? (C/C++) (template)
5.使用boost::array
請參考(原創) 如何使用boost::array? (C/C++) (boost)
(原創) 如何使用function template傳遞array? (C/C++) (template)
(原創) array傳進function該怎麼寫才好? (.NET) (C#)
(原創) 如何使用boost::array? (C/C++) (boost)
Reference
C++ Primer 4th P.242
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步