//vec.h
//包含处理venctor数组操作的一组函数模板
//ventry 2008-5-29
#include <vector>
//--------------------------------------------------------------------------------
//元素压入ventor数组
template<typename T>
inline int vec_PushBack( std::vector<T>& t_vec, const T& t )
{
t_vec.push_back(t);
return 1;
}
//--------------------------------------------------------------------------------
//跟据元素值删除第一个符合条件的元素
template<typename T>
int vec_DelObj( std::vector<T>& t_vec, const T& t )
{
for (int i=0; i<t_vec.size(); i++)
{
if(t_vec[i]==t)
{
t_vec.erase(t_vec.begin()+i);
return i;
}
}
return -1;
}
//--------------------------------------------------------------------------------
//根据下标删除符合条件的元素
template<typename T>
inline int vec_DelObj( std::vector<T>& t_vec, int i )
{
if(i<0 || i> t_vec.size()-1 ) return -1;
delete t_vec[i];
return 1;
}
//--------------------------------------------------------------------------------
//清除vector数组中所有元素
template<typename T>
int vec_Clear( std::vector<T>& t_vec )
{
int res = t_vec.size();
for (int i=t_vec.size()-1; i>=0; i--)
{
delete t_vec[i];
}
return res;
}
//--------------------------------------------------------------------------------
//main.cpp-----------------------------
#include <iostream>
#include "vec.h"
#include <string>
using namespace std;
//--------------------------------------------------------------------------------
class A
{//有个前提,它的所有子类都是单根继承或者它作为父类被继承时排在第一位,并且默认它和它的子类指针值是相同的
public:
A(int data){ m_data = data; vec_PushBack(instanc_vec,this);}
virtual ~A(){ vec_DelObj(instanc_vec, this); }
const static vector<A*>& GetObjVec(){ return instanc_vec; }
static int DelObj(int i){ return vec_DelObj( instanc_vec,i ); }
static int Clear(){ return vec_Clear(instanc_vec); }
virtual int put()=0;
int m_data;
protected:
static vector<A*> instanc_vec;
};
//--------------------------------------------------------------------------------
class B:public A
{
public:
B(int data):A(data){}
//virtual ~B(){ vec_DelObj(A::instanc_vec, (A*)this);}
int put(){ return 0; }
};
//--------------------------------------------------------------------------------
void pnt()
{
cout<<"---------------------------------------------"<<endl;
for (int i=0;i<A::GetObjVec().size();i++)
{
cout<<A::GetObjVec()[i]->m_data<<endl;
}
}
//----------------------------------------------------------------------------------
vector<A*> A::instanc_vec;
//----------------------------------------------------------------------------------
int main(void)
{
A *pa = new B(123);
B *pb = new B(546);
pnt();
//delete pa;
A::DelObj(1);
pnt();
A::DelObj(0);
pnt();
return 0;
}