C++ Primer(英語第5版) 閱讀日記 - 20201226
阿新 • • 發佈:2020-12-27
技術標籤:C++
3.5 Arrays
array和vector使用場景最基本的一點基於:是否知道總共有多少個元素。
- 如果知道,選擇array,因為訪問效率更高。
- 如果不知道,選擇vector,因為可以動態push。
array
的declartor
:<type> a[d],a是變數名,d是array的維度。
容易混淆的複雜定義
int *ptrs[10]; // ptrs是10個int的指標
int (*Parray)[10] = &arr; // Parray指向10個int的陣列
int *(&arry)[10] = ptrs; // array 是一個含有10個整數指標陣列的引用
儘管如果使用int
作為下標可以正常使用(觸發隱式conversion),但是,我們要注意,下標的實際型別為size_t
,是machine-specific的unsigned type。這一點知道32位,64位系統的人很自然能理解:地址空間可能隨OS位數變化的,所以我們索引資料型別也需要隨機器調整。
array與引用、指標
string nums[] = {"one", "two", "three"}; // string的array
string *p = &nums[0]; // p指向第一個元素
array和指標其實不分家。從記憶體空間角度上看,array分配了一段連續的虛擬地址,型別標定offset,下標告訴編譯器我們需要移動幾個offset。所以,C++其實也經常將array視作指標:
int ia[] = {0,1,2,3,4,5,6,7,8,9}; // ia is an array of ten ints
auto ia2(ia); // ia2 is an int* that points to the first element in ia
ia2 = 42; // error: ia2 is a pointer, and we can't assign an int to a pointer
同時,int*也可以使用下標,即方括號+偏移量訪問的方式
int i = ia[2]; // ia is converted to a pointer to the first element in ia
// ia[2] fetches the element to which (ia + 2) points
int *p = ia; // p points to the first element in ia
i = *(p + 2); // equivalent to i = ia[2]
int *p = &ia[2]; // p points to the element indexed by 2
int j = p[1]; // p[1] is equivalent to *(p + 1),
// p[1] is the same element as ia[3]
int k = p[-2]; // p[-2] is the same element as ia[0]
array與迭代器
從array的指標性質,我們可以結合library的begin
,end
(在iterator標頭檔案裡面),將array當作迭代器來使用:
// pbeg points to the first and pend points just past the last element in arr
int *pbeg = begin(arr), *pend = end(arr);
// find the first negative element, stopping if we've seen all the elements
while (pbeg != pend && *pbeg >= 0)
++pbeg;
array與別名(alias)
using int_array = int[4]; // new style type alias declaration; see § 2.5.1 (p.
68)
typedef int int_array[4]; // equivalent typedef declaration; § 2.5.1 (p. 67)
// print the value of each element in ia, with each inner array on its own line
for (int_array *p = ia; p != ia + 3; ++p) {
for (int *q = *p; q != *p + 4; ++q)
cout << *q << ' '; cout << endl;
}
3.5.4 C-Style Character Strings
之前提到過,string literals實際上是C-style的字串。他是以\0
作為結尾的char陣列,即null terminated。
C-style 的string literal在初始化中很容易被轉換為C++的string。但是,相反就需要member function來輔助了:
char *str = s; // error: can't initialize a char* from a string
const char *str = s.c_str(); // ok