C++ vector操作实例

#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();

 
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值