好久不用STL了,忘的差不多了,總結一下vector的使用方式,就不對每個方法做出詳細解釋了,只給出了如何用
void testVector() { int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //構造一個元素值全為2大小為10的vector vectorv1(10,2); //用指針構造 vector v2(a, a + 10); //用vector iterator構造 vector v3(v2.begin(), v2.end()); //構造一個和v1一樣的vector vector v4(v1); //使用[]操作符進行遍歷 cout << "=================v1===============" << endl; for (int i = 0; i < v1.size(); i++) { cout << v1[i] << " "; } cout << endl; vector ::iterator it; //得到第2個元素的iterator it = v2.begin() + 1; //移除第2個元素,返回移除元素後一個元素的iterator vector ::iterator erase_it = v2.erase(it); cout << *erase_it << endl; //移除之後就不能通過iterator訪問了 //cout << *it << endl; //通過iterator 遍歷 cout << "=================v2===============" << endl; for (it = v2.begin(); it != v2.end(); it++) { cout << *it << " "; } cout << endl; //逆序遍歷 cout << "=================v3 reserver======" << endl; vector ::reverse_iterator rit; for ( rit = v3.rbegin(); rit != v3.rend() ; rit++) { cout << *rit << " "; } cout << endl; cout << "=================v4 swap v3========" << endl; //交換v4和v3的內容 v4.swap(v3); for (int i = 0; i < v4.size(); i++) { cout << v4[i] << " "; } cout << endl; cout << "============v4 push pop insert======" << endl; //在v4末尾插入100 v4.push_back(100); //將末尾的100移除 v4.pop_back(); //在第二個元素位置插入1000 v4.insert(v4.begin() + 1, 1000); //在第二個元素位置插入2個200 v4.insert(v4.begin() + 1, 2, 200); //在第二個元素位置插入2個v1的開始到結束 v4.insert(v4.begin() + 1, v1.begin(), v1.end()); for (int i = 0; i < v4.size(); i++) { cout << v4[i] << " "; } cout << endl; cout << "============v4 clear empty size======" << endl; //清除v4中所有內容 v4.clear(); //檢查v4是否為空 if (v4.empty()) { cout << "v4 is empty" << endl; cout << "v4 size = "<
以下是測試結果