January 1, 2021

Coding10 - C++ Primer Part1

This is a C++ note for my own review and study.

一:函數原型 Function Prototype

C++中,函數聲明的代碼應該在函數調用之前;但是如果在函數調用之後定義函數,需要使用函數原型,舉例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// function prototype
void add(int, int);

int main()
{
// calling the function before declaration.
add(5, 3);
return 0;
}

// function definition
void add(int a, int b)
{
cout << (a + b);
}

函數原型:

1
void add(int, int);

函數原型為編譯器提供了函數名稱和參數信息,這樣可以在定義函數之前使用代碼來調用函數。

函數原型的語法為:

1
returnType functionName(dataType1, dataType2, ...);

二:C++函數類型

1.無傳參無返回值

第一個例子是判斷輸入值是不是素數:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# include <iostream>
using namespace std;

void prime(); // Function prototype
int main()
{
// No argument is passed to prime()
prime();
return 0;
}

// Return type of function is void because value is not returned.
void prime()
{
int num, i, flag = 0;

cout << "Enter a positive integer enter to check:";
cin >> num;

for(i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << num << "is not a prime number.";
}
else
{
cout << num << "is a prime number.";
}
}
2.無傳參有返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

int prime();

int main()
{
int num, i, flag = 0;

// No argument is passed to prime()
num = prime();
for (i = 2; i <= num/2; ++i)
{
if (num%i == 0)
{
flag = 1;
break;
}
}

if (flag ==1)
{
cout << num << " is not a prime number.";
}
else
{
cout << num << " is a prime number";
}
return 0;
}

// Return type of function is int
int prime()
{
int n;

printf("Enter a positive integer to check: ");
cin >> n;

return n;
}

prime()函數不從main()傳參數的情況下調用;而從用戶輸入獲取正整數,返回int類型數值給main()調用。

3.有傳參無返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;

void prime(int n);

int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;

// Argument num is passed to the function prime()
prime(num);
return 0;
}

// There is no return value to calling function. Hence, return type of function is void
void prime(int n)
{
int i, flag = 0;
for(i = 2; i <= n/2; ++i)
{
if (n%i == 0)
{
flag = 1;
break;
}
}

if (flag ==1)
{
cout << n << " is not a prime number.";
}
else
{
cout << n << " is a prime number.";
}
}

在這個例子中,用戶輸入的數值被存儲在變量num中,然後將num傳遞給函數prime(),又因為函數類型是void所以沒有值從函數返回。

4.有傳參有返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

int prime(int n);

int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;

// Argument num is passed to check() function
flag = prime(num);

if(flag == 1)
cout << num << " is not a prime number.";
else
cout << num << " is a prime number.";
return 0;
}

// This function return integer value.
int prime(int n)
{
int i;
for(i = 2; i <= n/2; ++i)
{
if(n%i == 0)
return 1;
}

return 0;
}

在本示例中,從用戶輸入獲取數值存儲在變量num中; 然後num被傳遞給prime檢查是否為質數,prime()返回int類型,1或0返回到main()函數中調用,是質數則返回0,不是質數賊返回1,然後將數值和文本打印。

🤔哪種方法更好?

那應該還是具體情況具體分析,沒有嚴格規定。


三:C++函數重載

在C++中,兩個函數可以有相同的名字,但是他們傳遞的參數類型必須不同:

1
2
3
4
5
// same name different arguments
int test() {}
int test(int a) {}
float test(double a) {}
int test(int a, double b) {}

在這裡,四個函數均為重載函數,重載函數衹要求參數類型不同,返回類型不作要求。

而以下為錯誤示例:

1
2
3
// Error code int&double均指代函數返回值的類型
int test(int a) {}
double test(int b) {}
1.重載函數使用不同類型參數的示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Program to compute absolute value
// Works for both int and float

#include <iostream>
using namespace std;

// function with float type parameter
float absolute(float var)
{
if (var < 0.0)
var = -var;
return var;
}

// function with int type parameter
int absolute(int var)
{
if (var < 0)
var = -var;
return var;
}

int main()
{

// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;

// call function with float type parameter
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}


/* OUTPUT
Absolute value of -5 = 5;
Absolute value of 5.5 = 5.5;
*/
2.重載函數使用不同數字參數的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

// function with 2 parameters
void display(int var1, double var2)
{
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}

// functon with double type single parameter
void display(double var)
{
cout << "Double number: "<< var << endl;
}

// function with int type single parameter
var display(int var)
{
cout << "Integer number: " << var << endl;
}

int main()
{
int a = 5;
double b = 5.5;

// call function with int type parameter
display(a);

// call function with double type parameter
display(b);

// call function with 2 parameters
display(a, b);

return 0;
}

/* OUTPUT
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5
*/

在這個例子中,display()函數被不同類型的參數喚起了三次。

Note:

在C++中,許多基礎庫的函數都是被重載的,例如sqrt()函數可以計算double float int等類型,所以sqrt()可能就是重載函數。


四:C++默認參數

在沒有參數輸入時,函數可以使用默認參數執行,我們可以從下面這張圖片了解到具體的邏輯:

1.當temp()被調用時,兩個默認的參數都會被使用;

2.當temp(6)被調用時,第一個int參數會使用輸入的值,第二個float參數會使用默認的值;

3.當temp(6, -2.3)被調用時,兩個默認的參數都會被覆蓋,而使用6和-2.3執行函數;

4.當temp(3.4) 被調用時,3.4會替換第一個默認參數,又因為int型需要是整數,所以實際傳遞的值為3;

下面是一個默認參數的代碼示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

// defining the default arguments
void display(char = '*', int = 3);

int main()
{
int count = 5;

cout << "No argument passed: ";
// *, 3 will be parameters
display();

cout << "First argument passed: ";
display('#');

cout << "Both arguments passed: ";
// $, 5 will be parameters
display('$', count);

return 0;
}

void display(char c, int count)
{
for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}

/* OUTPUT
No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$
*/

我們也可以在函數中定義默認值,下面的示例代碼於上文的運行結果相同:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

// defining the default arguments
void display(char c = '*', int count = 3)
{
for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}

int main()
{
int count = 5;

cout << "No argument passed: ";
// *, 3 will be parameters
display();

cout << "First argument passed: ";
// #, 3 will be parameters
display('#');

cout << "Both argument passed: ";
// $, 5 will be parameters
display('$', count);

return 0;
}
Remember

1.如果為參數提供了默認值,後續參數也都必須帶有默認值:

1
2
3
4
5
6
7
8
// Invalid
void add(int a, int b = 3, int c, int d);

// Invalid
void add(int a, int b = 3, int c, int d =4);

// Valid
void add(int a, int c, int b = 3, int d = 4);

2.如果我們在函數中定義了默認參數而不是在函數原型中,則必須在函數調用之前定義函數:

1
2
3
4
5
6
7
8
9
10
11
12
// Invalid code

int main()
{
// function call
display();
}

void display(char c = '*', int count = 5)
{
// code
}

五:C++存儲類別

在C++中有不同的存儲類別:local, global, static local, register and thread local.

每個變量在C++中有兩個功能:類型和存儲類(typle and storage class)。

Type可以指定變量的數據類型,例如:int, float, char等等。

Storage Class可以控制變量的兩個不同屬性:生存期(lifetime: 變量可以存在的時間長度)和範圍(scope: 哪一部分可以訪問)。

根據變量的存儲類別,它可以被分為5種主要的類型:

Local

在函數內定義的變量(defined inside function body between braces)被叫做局部變量。

作用範圍僅限定在定義它的函數內,局部變量只存在並且只能在函數內部訪問。

函數推出時,局部變量的生命期結束(被銷毀)。

局部變量的代碼示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

void test();
int main()
{
// local variable to main()
int var = 5;

test();

// illegal: var1 not declared inside main()
var1 = 9;
}

void test()
{
// local variable to test()
int var1;
var1 = 6;

// illegal: var not declared inside test()
cout << var;
}

變量var不能在函數test()內使用,var1不能在函數main()內使用。

Global

如果在所有函數之外都定義了變量,則將其稱為全局變量。

全局變量的應用範圍是整個程序。在聲明之後,可以在程序的任何部分使用和更改它。

同樣的,生命期在程序結束時結束。

全局變量的代碼示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

// Global variable declaration
int c = 12;

void test();

int main()
{
++c;

// Outputs 13
cout << c << endl;
test();

return 0;
}

void test()
{
++c;

// Outputs 14
cout << c;
}

/* OUTPUT
13
14
*/

c是程序中的全局變量,可以在main()test()兩個函數訪問。

Static Local

關鍵詞static用於指定靜態變量,例如:

1
2
3
4
5
6
··· ···
int main()
{
static float a;
······
}

靜態局部變量僅在聲明它的函數內部,但是生命期從調用函數開始,到程序結束時才結束。

局部變量和靜態變量的主要區別是,靜態變量的生命期持續到程序結束。

下面是靜態局部變量的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

void test()
{
// var is a static variable
static int var = 0;
++var;

cout << var << endl;
}

int main()
{
test();
test();

return 0;
}

/* OUTPUT
1
2
*/

在上面的程序中,test()函數被調用了兩次,第一次調用時,var被聲明為靜態變量並且初始化為0,並且被打印到屏幕上;當第二次調用函數時,變量var依然存在,並且加一後,打印在屏幕上;如果var只是局部變量,那麼輸出結果會是1,1。

Register

關鍵詞register用於指定註冊變量。

註冊變量類似於自動變量,僅存在特定的函數中。而且比局部變量還要快。

如果程序遇到了註冊變量,會將變量存儲在處理器的寄存器中,而不是註冊在內存中,這也是為什麼註冊變量比局部變量更快,但是註冊變量在C++ 11後被棄用了。

Thread Local Storage

線程本地存儲是一種機制,可以通過該機制分配變量,使得每個線程都有一個變量實例。關鍵詞thread_local來使用它。

了解更多:Thread Local Storage - The C++ Way


六:C++遞歸

調用自身的函數被稱為遞歸函數,並且這種技術被稱為遞歸。

C++中的遞歸
1
2
3
4
5
6
7
8
9
10
11
12
13
void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}

下圖顯示了遞歸調用的方式:

遞歸一直持續到滿足某些條件為止。

為了防止無限遞歸,可以在一個分支進行遞歸調用,另一個分支不進行遞歸調用的情況下使用if…else語句。

使用遞歸的數字階乘方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Factorial of n = 1*2*3...*n

#include <iostream>
using namespace std;

int factorial(int);

int main()
{
int n, result;

cout << "Enter a non-negative number: ";
cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}

int factorial(int n)
{
if ( n > 1)
{
return n * factorial(n - 1);
} else {
return 1;
}
}

/* OUTPUT
Enter a non-negative number: 4
Factorial of 4 = 24
*/

可以從下圖了解到程序階乘的邏輯:

如圖中所示,每次factorial()函數都會調用自身,並且n-1直到n=1時返回1。

遞歸的優缺點
  1. 優點
    • 它是我們的代碼更加清晰,簡短。
    • 在涉及數據結構和高級算法的問題中需要遞歸。
  2. 缺點
    • 於迭代程序相比,佔用大量堆棧空間。
    • 使用更多的處理器時間。
    • 與等效的迭代程序相比,調適會更加困難。

七:C++引用返回值

在C++中,我們不僅可以通過函數傳值,也可以通過引用的方法。

下面是通過引用的方法返回的代碼示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

// Global variable
int num;

// Function declaration
int& test();
int main()
{
test() = 5;

cout << num;

return 0;
}

int& test()
{
return num;
}

/* OUTPUT
5
*/

在上面的示例中,函數test()的返回類型是int&。所以函數的返回變量引用了變量num

Remember

當使用返回值時,你不能從函數返回一個常量:

1
2
3
4
5
// Error
int& test()
{
return 2;
}

你也不能返回一個局部變量:

1
2
3
4
5
6
// Error
int& test()
{
int n = 2;
return n;
}

八:C++數組

在C++中,數組是一個變量,可以存儲相同類型的多個數值。例如一個班27個學生,我們需要存儲所有學生的成績,不需要創建27個變量,我們衹需要創建一個數組即可:

1
double grade[27];

grade是數組名,包括了27個雙浮點數的元素。

在C++中,聲明數組後不能更改數組的大小和類型。

C++數組聲明
1
2
3
dataType arrayName[arraySize];

int x[6];

int - 存儲元素的類型

x - 數組名稱

6 - 數組的大小。

C++數組中的訪問元素

在C++中,數組的每個元素都與一個數字關聯,這個數字就是數組索引。我們可以通過索引來訪問數組的元素。

1
2
// syntax to access array elements
array[index];

數組索引都是以0為起始,如果數組的大小為n則最後一個元素存儲在(n-1)處,x[5]是最後一個元素。

數組的元素具有連續的地址。例如起始地址x[0]為2120d,那麼下一個元素x[1]的地址2124d,x[2]的地址為2128d;為什麼是+4呢?因為int佔4個字節的大小。

C++數組初始化

在C++中,可以聲明時初始化數組,例如:

1
2
// declare and initialize and array
int x[6] = {19, 10, 8, 17, 9, 15};

在聲明時的另一種初始化的方法:

1
2
// declare and initalize an array
int x[] = {19, 10, 8, 17, 9, 15};

我們不需要設置數組的大小,這種情況下,編譯器會自動計算大小。

C++數組中的空數據

在C++中,輸入數組的大小為n,我們最多可以存儲ñ的元素,如果我們存儲的元素小於ñ時:

1
2
// store only 3 elements in the array
int x[6] = {19, 10, 8};

我們僅有三個元素進行了初始化,其餘位置會被編譯器分配隨機值,通常是0。

示例一:插入和打印數組數據
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9
mark[3] = 9;

// take input from the user
// store the value at third position
cin >> mark[2];

// take input from the user
// insert at ith position
cin >> mark[i-1];

// print first element of the array
cout << mark[0];

// print ith element of the array
cout >> mark[i-1];

下面代碼演示如何顯示數組元素:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int main()
{
int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

// Printing array elements
// using rage based for loop
for (coust int &n : numbers)
{
cout << n << " ";
}

cout << "\nThe numbers are: ";

// Printing array elements
// using traditional for loop
for (int i = 0; i < 5; ++i)
{
cout << numbers[i] << " ";
}
return 0;
}

/* OUTPUT
The numbers are: 7 5 6 12 35
The numbers are: 7 5 6 12 35
*/

在這裡,我們使用了一個for循環來幫助我們打印numbers[i]的元素。

NOTE:

在rage based的循環中,我們使用了代碼const int &n而不是int n,是因為:

1.使用int n只需在每次迭代中,將數組元素複製到變量ñ,這不是高效的內存方法。&n直接使用數組元素的內存地址來訪問數據,而不需要將它複製到新的變量中,可以節省內存。

2.我們只需要打印數組元素,而不需要修改它們,因此我們使用const方法來避免意外更改數組的值。

示例二:從用戶獲取輸入並存儲入數組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;

int main()
{
int numbers[5];

cout << "Enter 5 numbers: " << endl;

// store input from user to array
for (int i = 0; i < 5; ++i)
{
cin >> numbers[i];
}

cout << "The numbers are: ";

// print array elements
for (int n = 0; n < 5; ++n)
{
cout << numbers[n] << " ";
}

return 0;
}

/* OUTPUT
1
2
3
4
5
The numbers are: 1 2 3 4 5
*/

我們通過一個for循環來迭代i=0i=4;將用戶輸入的數據存儲在numbers[],然後通過另外一個for循環來打印。

示例三:使用for循環來顯示數組元素的總和和平均值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
using namespace std;

int main()
{

// initialize an array without specifying size
double numbers[] = {7, 5, 6, 12, 35, 27};

double sum = 0;
double count = 0;
double average;

cout << "The numbers are: ";

// print array elements
// use of range-based for loop

for(const double &n : numbers)
{
cout << n << " ";

//caculate the sum
sum += n;

// cout the no. of array elements
++count;
}

// print the sum
cout << "\nTheir Sum = " << sum << endl;

// find the average
average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}

/* OUTPUT
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.3333
*/

我們使用了range-based循環,而不是普通的for循環,因為普通的for循環需要我們指定迭代次數,而range-based循環不需要指定。

C++數組越界

如果我們聲明了一個大小為10的數組,這個數組可以索引的元素從0~9。

但是,如果我們索引10或10以上的元素,則會導致未定義的行為。


九:C++多維數組

在C++中,我們可以創建一個數組的數組,稱為多維數組,例如:

1
int x[3][4];

這裡的x是一個二維數組,他最多可以容納12個元素。

我們可以把數組視為具有三行四列的矩陣:

三維數組也有類似的方法,例如:

1
float x[2][4][3];

這個數組最多可以容納24個元素,即:2x4x3 = 24。

多維數組的初始化

像普通數組一樣,我們可以通過多種方式初始化多維數組。

1.二維數組的初始化

1
int test[2][3] = {2, 4, 5, 9, 0, 19};

下面是一個更好的初始化素組的方法:

1
int test[2][3] = { {2, 4, 5}, {9, 0, 19} };

這就是為什麼我們的數組有兩行三列的原因。

2.三維數組的初始化

1
2
int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23, 
2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

同樣,我們可以更好的初始化它:

1
2
3
4
int test[2][3][4] = { 
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};

怎麼看出來它是三維數組?

第一維的值是2,因此構成第一維的兩個元素是:

1
2
element1 = {{3423},{0-3911},{2312232}}
element2 = {{134563},{ 5935},{5149}}

第二維的值是3,因此:

1
2
{3,4,2,3},{0,-3,9,11},{23,12,23,2} for Element 1
{13,4,56,3},{ 5,9,3,5},{5,1,4,9} for Element 2

最後一維,即是構成第二維的4個數。

示例一:二維數組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// C++ Program to display all elements
// of an initialised two dimensional array

#include <iostream>
using namespace std;

int main()
{
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};

// use of nested for loop
// access rows of the array
for (int i = 0; i < 3; ++i)
{

//access columns of the array
for (int j = 0; j < 2; ++j)
{
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}

return 0;
}

/* OUTPUT
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
*/

外循環從i == 0i == 2訪問矩陣的行。

內循環從j == 0j == 1訪問矩陣的列。

最後我們打印了數組的元素。

示例二:獲取二維數組的輸入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;

int main()
{
int numbers[2][3];

cout << "Enter 6 numbers: " << endl;

// Storing user input in the array
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

// Printing array elements
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
}
}

return 0;
}

/* OUTPUT
Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6
*/
示例三:三維數組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// C++ Program to Store value entered by user in
// three dimensional array and display it.

#include <iostream>
using namespace std;

int main()
{
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] =
{
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};

//Displaying the values with proper index.
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
cout << "test[" << i << "][" << j << "][" << k <<'] = ' << test[i][j][k] << endl;
}
}
}

return 0;
}

/* OUTPUT
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
*/

十:C++將數組傳遞給函數

在C++中,我們可以將數組作為參數傳遞給函數,同樣的,也可以從函數返回數組。

將數組作為參數傳遞的語法:

1
2
3
4
returnType functionName(dataType arrayName[arraySize])
{
//code
}

讓我們來看看一個例子

1
2
3
4
int total(int marks[5])
{
// code
}
示例一:將一維數組傳遞給函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// C++ Program to display marks of 5 students

#include <iostream>
using namespace std;

// declare function to display marks
// take a 1d array as parameter
void display(int m[5])
{
cout << "Displaying marks: " << endl;

// dislay array elements
for (int i = 0; i < 5; ++i)
{
cout << "Student" << i + 1 << ": " << m[i] << endl;
}
}

int main()
{
// declare and initialize an array
int marks[5] = {88, 76, 90, 61, 69};

// call display function
// pass array as argument
dislay(marks);

return 0;
}

/* OUTPUT
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
*/

1.當我們傳遞數組作為參數來調用函數時,我們衹需要使用數組的名稱dislay(marks)

2.但是,在display()的函數中我們需要定義數組的聲明。

1
void display(int m[5])

3.參數函數int m[5]可以轉換為int* m,這和數組marks指向相同的地址。這意味著當我們在函數主體中操作m[5]的時候,我們實際上是在操作原始數組marks

示例二:將多維數組傳遞給函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// C++ Program to display the elements of two
// dimensional array by passing it to a function

#include <iostream>
using namespace std;

// define a function
// pass a 2d array as a parameter
void display(int n[3][2])
{
cout << "Displaying Values: " << endl;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 2; ++j)
{
cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
}
}
}

int main()
{
// initialize 2d array
int num[][2] =
{
{3, 4},
{9, 5},
{7, 1}
};

// call the function
// pass a 2d array as an argument
display(num);

return 0;
}

/* OUTPUT
Displaying Values:
num[0][0]: 3
num[0][1]: 4
num[1][0]: 9
num[1][1]: 5
num[2][0]: 7
num[2][1]: 1
*/

在上面的程序中,我們定義了一個名為display()的函數,將一個二維數組int n[][2]作為參數打印。

在調用函數時,我們只需要將二維數組的名稱作為函數參數傳遞display(num)

NOTE:

我們不需需要指定數組中的行數,但是需要指定列數,這也是為什麼我們使用的是int n[][2]

C++從函數返回數組

我們還可以從函數返回一個數組,通常是在指針的幫助下返回數組的第一個元素地址。

About this Post

This post is written by Siqi Shu, licensed under CC BY-NC 4.0.