/********************************************************************
purpose: std::vector使用测试
author: dotlive
*********************************************************************/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Person
{
Person():Id(0), Name(""), Sex(0) {}
Person(int rId, const char* rName, int rSex):Id(rId), Name(rName ? rName : ""/*Note*/), Sex(rSex) {}
int Id;
std::string Name;
int Sex;
};
typedef std::vector<Person*> Friends;
typedef Friends::iterator PersionIter;
void main()
{
Friends myFriend;
int iCnt = 0;
// Init
for (int i=1; i<=10; ++i)
{
char szTemp[20] = {0};
sprintf_s(szTemp, sizeof(szTemp), "Name-%02d", i);
Person* pPerson = new Person(i, szTemp/*NULL*/, 1);
myFriend.push_back(pPerson);
}
// Output
for (PersionIter iter = myFriend.begin(); iter != myFriend.end(); ++iter)
{
cout<<"Person_"<<(*iter)->Id<<"'s info:Name="<<(*iter)->Name<<", Sex="<<(*iter)->Sex<<endl;
}
// Delete
for (PersionIter iter = myFriend.begin(); iter != myFriend.end(); ++iCnt)
{
/*
// Delete partly.
if (iCnt % 3 == 0)
{
delete (*iter);
iter = myFriend.erase(iter);
}
else
{
++iter;
}
*/
// Delete totally.
delete (*iter);
iter = myFriend.erase(iter);
}
getchar();
}