以下是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; }
以下是执行结果:
|