STL.vector容器刪除單個元素、部分元素、全部元素

騎在木馬上的黑客發表於2018-04-23

當容器中的元素為指標時,我們刪除容器中元素的時候,也要注意使用delete ptr;刪除堆堆物件例項,以免造成記憶體洩露的問題。

下面我以vector容器為例,也適用於其它容器(deque、map、set)。

#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
using namespace std;

//C++中的結構體相當於一個類,變數預設為public
typedef struct SPerson{
	string strName;//姓名
	string strAddr;//住址
	string strTel;//聯絡電話
	SPerson(string name, string addr, string tel)
	{
		strName = name; strAddr = addr; strTel = tel;
		cout << "Construct Person : " << strName << endl;
	}
	~SPerson()
	{
		cout << "Destruct Person : " << strName << endl;
	}
}SPERSON, *PSPERSON;

void DispVector(vector<PSPERSON>& vPerson)
{
	cout.setf(std::ios::left);
	cout << "Begin>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << endl;
	for(vector<PSPERSON>::iterator it = vPerson.begin(); it != vPerson.end(); it++){
		cout << setw(12) << (*it)->strName << setw(12) << (*it)->strAddr << setw(12) << (*it)->strTel << endl;
	}
	cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>End" << endl << endl;
}

void main()
{
	vector<PSPERSON> vPerson;
	PSPERSON pPerson = NULL;

	cout << "Insert Data : " << endl;
	pPerson = new SPERSON("Tony", "WuHan", "021-1111111");
	vPerson.push_back(pPerson);

	pPerson = new SPERSON("Bob", "HangZhou", "0571-1111111");
	vPerson.push_back(pPerson);
	pPerson = new SPERSON("Mary", "HangZhou", "0571-2222222");
	vPerson.push_back(pPerson);

	pPerson = new SPERSON("ZhangSan", "BeiJing", "010-1111111");
	vPerson.push_back(pPerson);
	pPerson = new SPERSON("LiSi", "BeiJing", "010-2222222");
	vPerson.push_back(pPerson);
	pPerson = new SPERSON("WangWu", "BeiJing", "010-3333333");
	vPerson.push_back(pPerson);

	DispVector(vPerson);


	//指定姓名刪除(刪除單個)
	cout << "Before deleting... size : " << vPerson.size() << endl;
	for(vector<PSPERSON>::iterator it = vPerson.begin(); it != vPerson.end(); it++){
		pPerson = (*it);
		if(pPerson != NULL && pPerson->strName == "Tony"){
			delete pPerson; it = vPerson.erase(it); break;
		}
	}
	cout << "After deleted... size : " << vPerson.size() << endl;
	DispVector(vPerson);

	//指定區域刪除(刪除多個)
	cout << "Before deleting... size : " << vPerson.size() << endl;
	for(vector<PSPERSON>::iterator it = vPerson.begin(); it != vPerson.end(); ){
		pPerson = (*it);
		if(pPerson != NULL && pPerson->strTel.substr(0, 4) == "0571"){
			delete pPerson; it = vPerson.erase(it); 
		}
		else it++;
	}
	cout << "After deleted... size : " << vPerson.size() << endl;
	DispVector(vPerson);

	//全部刪除
	cout << "Before deleting... size : " << vPerson.size() << endl;
	for(vector<PSPERSON>::iterator it = vPerson.begin(); it != vPerson.end(); ){
		pPerson = (*it);
		if(pPerson != NULL)			delete pPerson; 
		it = vPerson.erase(it); 
	}
	cout << "After deleted... size : " << vPerson.size() << endl;
	DispVector(vPerson);

}


相關文章