自定义std vector的派生类search_vector加入sort、search函数

比较函数

template<typename T>class KdLess//此模板函数主要用于比较指针对象的比较
{
public:
	//指针对象的比较定义为指针指向对象的比较(需要为指向对象重载的“<”操作符)
	bool operator () (const T* l, const T* r)const
	{
		ASSERT((NULL != l) && (NULL != r));
		return (*l) < (*r);//转入对象重载的“<”操作符
	}
};

search_vector

/*linlee@2007-07-31
此类可以选择性使用,使用方法并不比直接使用vector方便多少.
详细使用例子参见后面被注释掉的代码,此代码也可以作为直接使用vector搜索的例子。
*/
namespace std{
	template<typename _Ty,				//设置为大类型的指针!!!!!!
		typename _Pr = less<_Ty>,		//此处提供小于操作的函数对象
		typename _Ax = allocator<_Ty> >	//此处无需提供
	class search_vector
		: public vector<_Ty, _Ax>		//继承自vector,免得写一堆函数
	{
	public:
		typedef vector<_Ty, _Ax> _Mybase;				//基类
		typedef _Vector_iterator<_Ty, _Alloc> iterator;	//
		typedef pair<iterator, iterator> iterator_pair;	//find函数的返回类型
	public:
		void sort(){
			std::sort(begin(), end(), _Pr());//排序,此后才能有效查找
		}
		iterator_pair find(_Ty key_data){//调用此函数之前必须调用过search_vector::sort(),且不再有向量内指针的变更
			return equal_range(begin(), end(), key_data, _Pr());
		}
		search_vector():_Mybase(){}
	};
};

使用示例代码

#include <stdlib.h>	//for rand()

#include <vector>
using std::vector;
#include <algorithm>
using std::generate_n;
using std::sort;

#include "kd_delete.h"

#include <iostream>
using std::cout;
using std::endl;
#include "search_vector.h"
using std::search_vector;

int g_iCount = 0;	//记载BigClassSample构造函数的运行次数
int g_iCount_d = 0;	//记载BigClassSample析构函数的运行次数

class BigClassSample
{
public:
	int get_key()const{return iKey;}
	bool operator<(const BigClassSample &temp)const{
		return iKey < temp.iKey;
	}
	static BigClassSample * rand_one(){
		return new BigClassSample;
	}
	explicit BigClassSample(int it):iKey(it){}
	BigClassSample(){
		iKey = rand();
		++g_iCount;
	}
	~BigClassSample(){
		++g_iCount_d;
	}
private:
	int iKey;
	int i[7];
};

template<typename T>class kd_less{
public:
	bool operator()(T* l, T* r)const{
		return (*l) < (*r);
	}
};

typedef search_vector<BigClassSample*, kd_less<BigClassSample> > BigClassSample_svec;


const int VecSize = 1000;
int main(int argc, char* argv[])
{
	BigClassSample_svec svBig;
	svBig.reserve(VecSize);
	generate_n(back_inserter(svBig), VecSize, BigClassSample::rand_one);//生成向量中的内容
	//
	cout << "before sort :" << endl;
	for(int i = 0; i < VecSize; ++i)
		cout << svBig[i]->get_key() << "	";
	cout << endl << endl;
	//
	svBig.sort();//排序
	BigClassSample tbig(10040);
	BigClassSample_svec::iterator_pair ipair = svBig.find(&tbig);//查找
	if(ipair.first == ipair.second)
		cout << "not found\n";
	else
		cout << "found " << int(ipair.second - ipair.first) << " value(s), value's key = " << (*(ipair.first))->get_key() << endl << endl;
	//
	cout << "after sort :" << endl;
	for(int i = 0; i < VecSize; ++i)
		cout << svBig[i]->get_key() << "	";
	cout << endl << endl;
	//
	DelObj(svBig);//内存释放
	//
	cout << "构造函数运行的次数:	" << g_iCount << endl;
	cout << "析构函数运行的次数:	" << g_iCount_d << endl;
	//
	getchar();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43172531/article/details/103764449