1. 程式人生 > >靜態陣列與動態陣列 c形式與c++形式的字串

靜態陣列與動態陣列 c形式與c++形式的字串

既然要學習陣列,那麼先來了解一下陣列是什麼,為什麼要有陣列的出現吧。
陣列:陣列是一系列具有相同型別元素的集合。
陣列的出現是為了當定義較多變數時,使操作更簡單化,直觀化。

靜態陣列與動態陣列

*靜態陣列:*在編譯階段,陣列包含的元素數以及佔用的記憶體量是不變的。
可分為:一維陣列與多維陣列
一維陣列的定義:

int numbers[200]={0};
char mycharacters[5];

多維陣列的定義:

int ThreeRowsThreeCols [3][3]={{1,2,3},{4,5,6},{7,8,9}};

動態陣列:靜態陣列在未知數量的情況下,需要分配大量的記憶體。而動態陣列為了減少佔用記憶體,在執行階段根據需要增大動態陣列。
動態陣列的定義需要用到:vector<資料型別>
下面是動態陣列的例項:建立一個int型別的動態陣列,並動態的增大容量


#include "stdafx.h"
#include"iostream"
#include"string"
#include "vector"
using namespace std;

int main()
{
	vector<int> dynArrNums (3);
	dynArrNums[0] = 1;
	dynArrNums[1] = 3;
	dynArrNums[2] = 4;
	cout << "the size of array : " << dynArrNums.size() << endl;
	int otherdynArraynums = 0;
	cout << "Enter the otherdynArraynums";
	cin >> otherdynArraynums;
	dynArrNums.push_back(otherdynArraynums);

	cout << "the size of array : " << dynArrNums.size() << endl;
	system("pause");
	return 0;
}

結果如下圖所示:
在這裡插入圖片描述
注意:
1 靜態陣列宣告定義後,他們的長度在編譯階段是固定不變的,它既不能儲存更多的資料,即使有部分元素未被使用,它的記憶體空間也不會減少。
2 在定義靜態陣列時,務必初始化陣列,否則會包含未知數值。
3 訪問陣列元素時,注意索引應該比最大長度少1,不應超越陣列的邊界。
4在使用動態陣列時,務必新增標頭檔案 # include "vector"

C風格的字串和c++字串:std:string

C風格的字串
下面用一個簡單的例子解釋:


#include "stdafx.h"
#include "iostream"
using namespace std;

int main()
{
	char Sayhellotoc[] = { 'h','e','l','l','o',' ','\0' };
	cout << "the size of Sayhellotoc : " << sizeof(Sayhellotoc) <<endl;
	cout << "the length of Sayhellotoc : " << strlen(Sayhellotoc) << endl;
	Sayhellotoc[4] = '\0';
	cout << "the size of Sayhellotoc : " << sizeof(Sayhellotoc) << endl;
	cout << "the length of Sayhellotoc : " << strlen(Sayhellotoc) << endl;
	system("pause");
	return 0;
}


輸出結果如下圖所示:
在這裡插入圖片描述
注意:
由以上輸出的結果可知:
1 定義的變數型別為char,在初始化字串時,末尾必須有 ‘\0’。
2 ‘\0’只會佔據字串記憶體空間的大小,不會影響字串的長度。
3 在給已知的字串分配記憶體空間的大小,陣列的長度=字串的長度+1
4 字串的中間插入‘\0’時,陣列的長度不會改變,但是字串的長度會減少 。


c++字串:std:string

同樣用一個例子來解釋:


#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;


int main()
{
	string SayhellotoC("hello");
	cout << "the size of the SayhellotoC : " << SayhellotoC.length() << endl;

	system("pause");
	return 0;
}


結果如下圖所示:
在這裡插入圖片描述
注:
從上面結果可以看出:
1定義型別為string,與char不同。
2 不需要在末尾新增‘\0’,也不需要像C形式,一個一個的初始化字串,更加簡單、快捷;同時也防止了忘記新增轉義字元而超越陣列的邊界;
3 需要引入標頭檔案 #include “string”
4 當檢視字串長度時與C不同,運用 stingname.length形式檢視。