// 1.正常使用包含指针的结构体 // 2.正常使用元素类型为指针的vector #include<string.h> #include<stdio.h> #include<memory.h> #include <malloc.h> #include <vld.h> #include <vector> using std::vector; struct student { int name; char *data; }; template <typename T> void ClearVector(vector<T>& v) { vector<T>::iterator it, itEnd = v.end(); for (it=v.begin();it!=itEnd;it++) { if (*it != NULL) { delete *it; *it = NULL; } } vector<T> vtTemp; vtTemp.swap(v); } void AddStudent(vector<student*>& strVec, int name, char* data) { char szData[100];// 这里使用一个字符数组,防止data被外部释放。 strcpy_s(szData, strlen(data) + 1, data); struct student *ptsdu=(student*)malloc(sizeof(student)); memset(ptsdu,0,sizeof(student)); ptsdu->name = name; ptsdu->data = szData; strVec.push_back(ptsdu); } vector<student*> g_stuVec; void main(void) { char data1[] = "ddbb"; char data2[10]; strcpy_s(data2, 10, "bb"); AddStudent(g_stuVec, 1, data1); AddStudent(g_stuVec, 2, data2); ClearVector(g_stuVec); system("pause"); }