以下是Vector容器用戶總結
--------------------------------------------------------------------------------------------------- 幾個介紹vector容器還不錯的文章鏈接: http://blog.csdn.net/fm0517/archive/2009/06/09/4254099.aspx
---------------------------------------------------------------------------------------------------
// Test_20110513_1036.cpp : Defines the entry point for the console application. //
#include "stdafx.h"
#include <vector> #include <iostream> using namespace std;
int _tmain(int argc, _TCHAR* argv[]) { //創建vector容器 vector<int> vInt; //也可以下面這樣初始化,表示將所有的元素初始化為 //vector<int> vInt(0); //添加元素 for (vector<int>::value_type i = 0; i < 10; i++) vInt.push_back(i + 1); //輸出元素 cout << "-------------------------------------------------------" << endl << "操作:添加元素" << endl; for (vector<int>::iterator iter = vInt.begin(); iter != vInt.end(); iter++) cout << *iter << endl; //erase操作----其實就是刪除指定的某個元素 cout << "-------------------------------------------------------" << endl << "操作:erase操作" << endl; for (vector<int>::iterator iter3 = vInt.begin(); iter3 != vInt.end(); iter3++) { if (*iter3 == 8) { iter3 = vInt.erase(iter3); break; } } for (vector<int>::iterator iter4 = vInt.begin(); iter4 != vInt.end(); iter4++) cout << *iter4 << endl;
//刪除最后一個元素,方法一 cout << "-------------------------------------------------------" << endl << "操作:刪除最后一個元素之方法一" << endl; if (vInt.size() > 0) { vector<int>::iterator iterEnd = vInt.end() - 1; /*iterEnd = */vInt.erase(iterEnd); //輸出 for (vector<int>::iterator iter5 = vInt.begin(); iter5 != vInt.end(); iter5++) cout << *iter5 << endl; }
//刪除最后一個元素,方法二 cout << "-------------------------------------------------------" << endl << "操作:刪除最后一個元素之方法二" << endl; if (vInt.size() > 0) { vector<int>::iterator iterEnd2 = vInt.end() - 1; vInt.pop_back(); //輸出 for (vector<int>::iterator iter5 = vInt.begin(); iter5 != vInt.end(); iter5++) cout << *iter5 << endl; }
//清空所有數據元素 vInt.clear(); //輸入元素 cout << "-------------------------------------------------------" << endl << "操作:清空元素" << endl; for (vector<int>::iterator iter2 = vInt.begin(); iter2 != vInt.end(); iter2++) cout << *iter2 << endl;
return 0; }
以下是執行結果:
|