#include<iostream.h>
#pragma warning(disable: 4786)
#include <vector>
using namespace std;
//(0)定義相關類型
typedef struct
{
int id;
char name[20] ;
int age;
}T_student;
//vector
typedef vector< T_student*, allocator<T_student*> > VECTORSTUDENT;
typedef vector< T_student*, allocator<T_student*> >::iterator ITVECTOR;
VECTORSTUDENT stuVector;
void testAddVector()
{
T_student * pStu=NULL;
for(int i=0;i<3;i++)
{
pStu=new T_student();
memset(pStu,0,sizeof(T_student));
pStu->id=i+1;
strcpy(pStu->name,"name");
pStu->age=20+i;
stuVector.push_back(pStu);
}
}
void printAll()
{
printf("All data is:/n");
ITVECTOR itStu;
for (itStu = stuVector.begin(); itStu != stuVector.end(); itStu++)
{
T_student * pTemp=*itStu;
printf("/tid=%d/tname=%s/tage=%d/n",pTemp->id,pTemp->name,pTemp->age);
}
}
void deleteAll()
{
ITVECTOR itStu;
for (itStu = stuVector.begin(); itStu != stuVector.end(); itStu++)
{
T_student * pTemp=*itStu;
delete pTemp;
pTemp=NULL;
}
stuVector.clear();
}
void deleteOne(int id)
{
ITVECTOR itStu;
for (itStu = stuVector.begin(); itStu != stuVector.end(); itStu++)
{
T_student * pTemp=*itStu;
if(pTemp->id==id)
{
// vector 沒有remove 函數
//stuVector.remove(pTemp);
stuVector.erase(itStu);
delete pTemp;
pTemp=NULL;
break;
}
}
}
T_student * getOne(int index)
{
//只有vector 纔有 []操作符
return stuVector[index];
/* 下面的方法也可以
ITVECTOR itStu;
for (itStu = stuVector.begin(); itStu != stuVector.end(); itStu++)
{
T_student * pTemp=*itStu;
if(pTemp->id==id)
{
return pTemp;
}
}
return NULL;
*/
}
void main()
{
testAddVector();
printAll();
deleteOne(1);
printAll();
deleteAll();
printAll();
}