Vector ======== Introduction -------- Vector是c++中陣列的替代型態,可以自主控制需要的記憶體。 Vector可以任意增加陣列長度及資料的數量,也可任意插入或刪除指定位置的資料。 基礎運用 -------- 使用vector需要加入標頭檔vector ex: ```c #include ``` 宣告新vector的語法 ```c vector vector_name(amount,element); ``` ex: ```c vector acm(3,4); vector csie(5);//未指定數字會補 0 ``` 嘗試印出兩vector內容 output: ```c acm : 4 4 4 csie : 0 0 0 0 0 ``` 也可以直接建立空白的vector ex: ```c vector acm; ``` 此外也可以使用陣列為基礎來建構vector,將陣列原有的資料放入vector中 如此的指定方式,需要提供的參數為起始位址與結束位址 ex: ```c int array[5]={1,2,3,4,5}; vector ncku(array,array+5);//1 2 3 4 5 vector csie(array+1,array+4);//2 3 4 ``` Member functions ---------------------------- ### operator[] 中括號[]的用法與array相同,指的是vector中的指定項元素 ```c int array[5]={1,2,3,4,5}; vector ncku(array,array+5); cout << ncku[2] << endl; ``` output: ```c 3 ``` ### iterator迭代器/.begin() /.end() 若要讀取資料的話也可以定義iterator來進行進一步的操作 ```c vactor ::iterator it; vactor ::iterator it2; ``` .begin()會將iterator指向第一筆資料 .end()會將iterator指向最後一筆資料 完整程式碼範例 ex: ```c #include #include using namespace std; vector acm(3,4); vector::iterator it; void vector_print(vector v){ cout << "The vector contains these elements : " << endl; for(it = v.begin(); it != v.end(); it++){ cout << *it << " "; }//prints the vector from the first element to the last element cout << endl; } int main(){ int n; vector_print(acm); return 0; } ``` Output: ```c The vector contains these elements : 4 4 4 ``` ### .push_back()/.pop_back() .push_back()會將小括號內的資料加入vector尾端 而.pop_back則會刪去最後面的資料 ex: ```c char ar[5]={'a','b','c','d','e'}; vector csie(ar,ar+5); vector::iterator it; vector_print(csie); csie.push_back('f'); vector_print(csie); csie.push_back('g'); vector_print(csie); csie.pop_back(); vector_print(csie); csie.pop_back(); vector_print(csie); ``` output: ```c a b c d e a b c d e f a b c d e f g a b c d e f a b c d e ``` ### .size() .size會回傳vector大小 ```c vector acm(5); cout << acm.size() << endl; ``` output: ```c 5 ``` ### .clear() / .empty() ### .erase() / .insert() ### .assign()