C++ vector容器释放内存应注意的地方(一)

//#include <iostream>
//#include <vector>
//#include <stdio.h>
//#include <boost/date_time.hpp>
//using namespace std;
//using namespace boost::gregorian;
////返回dtLastDatetime相对于dtCurDatetime日期的第几周
//int GetOrderWeek(const date &dtLastDatetime, const date &dtCurDatetime);
//
//const int MAX_SIZE = 100*1024;
//
//struct Person
//{
//	string  strName;
//	int		nAge;
//	char  ch[MAX_SIZE];
//};
//
//typedef struct tagRecord
//{
//	string     strNumber;
//	vector<Person> vcPersonList;
//}Record;
//
//void MyMethod() 
//{
//	Record record;
//	record.strNumber = "100000285";
//	vector<Person> *pPersonList = &record.vcPersonList;
//
//
//	Person person1;
//	person1.nAge = 22;
//	person1.strName = "sunkaifang";
//	pPersonList->push_back(person1); 
//
//
//	Person person2;
//	person2.nAge = 23;
//	person2.strName = "ganquafnu";
//
//	pPersonList->push_back(person2);   
//
//
//	vector<Person>::reverse_iterator tem;
//	cout << record.strNumber << endl;
//	for (tem = record.vcPersonList.rbegin(); tem != record.vcPersonList.rend(); ++tem )
//	{
//		cout << tem->strName << "  " << tem->nAge << endl;
//	}
//	cout << record.vcPersonList.size() << record.vcPersonList.capacity() << endl;
//	record.vcPersonList.clear();
//	vector<Person>().swap(*pPersonList);//这中方法是可以内存空间的
//	cout << record.vcPersonList.size() << record.vcPersonList.capacity() << endl;
//}
//
//void main()
//{
//	MyMethod();
//	int wait;
//	cin >> wait;
//}
 
 
 
#include <iostream>
#include <vector>
#include <stdio.h>
#include <boost/date_time.hpp>
using namespace std;
using namespace boost::gregorian;
const int MAX_SIZE = 100*1024*1024;
 
struct Person
{
	string  strName;
	int		nAge;
	char    num[MAX_SIZE] ;
};
 
typedef struct tagRecord
{
	string     strNumber;
	vector<Person*> vcPersonList;
}Record;
void MyMethod() 
{
	Record record;
	record.strNumber = "100000285";
 
	Person *person = new Person();
	person->nAge = 22;
	person->strName = "sunkaifang";
	record.vcPersonList.push_back(person); 
 
 
	person = new Person();
	person->nAge = 23;
	person->strName = "ganquafnu";
 
	record.vcPersonList.push_back(person);   //注意这类,拷贝一份Person结构体
	
 
	vector<Person*>::reverse_iterator tem;
	cout << record.strNumber << endl;
	for (tem = record.vcPersonList.rbegin(); tem != record.vcPersonList.rend(); ++tem )
	{
		if (*tem != NULL)
		{
			cout << (*tem)->strName << "  " << (*tem)->nAge << endl;
			delete *tem;
		}
		*tem = NULL;
	}
	
	//至此所有的new出来的内存空间全部释放了
}
 
void main()
{
	MyMethod();
 
	int wait;
	cin >> wait;
}
posted @ 2013-06-22 09:33  Predator  阅读(643)  评论(0编辑  收藏  举报