关闭

函数配置器的举例

43人阅读 评论(0) 收藏 举报
分类:

配置器的定义:

在c++STL中的头文件<memory>中有标准适配器的声明如下:

namespace std
{
	template < class T>
	class allocator
	{
	public:
		//型别
		typedef size_t size_type;
		typedef ptrdiff_t difference_type;
		typedef T* pointer;
		typedef const T * const_pointer;
		typedef T & reference;
		typedef const T & const_reference;
		typedef T value;
		template <class U>struct rebind
		{
			typedef allocator<U>other;
		};
	public:
		//配置类的成员函数
		allocator()throw();
		allocator(const allocator&)throw();
		template<class U>
		allocator(const allocator<U>&)throw();
		~allocator()throw();

		pointer address(reference value)const;
		const_pointer address(const_reference value)const;
		size_type max_size()const throw();
		pointer allocator(size_type num, allocator<void>::const_pointer hint = 0);
		void construct(pointer p, const T&value);
		void destroy(pointer p);
		void deallocator(pointer p, size_type num);
	};
}

举例:

#include<memory>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
template<class T>
void printV(const vector<T>&v)//输出容器
{
	copy(v.begin(), v.end(), ostream_iterator<T>(cout, ","));
	cout << endl;
}


void printAl( allocator<int>::pointer vv, size_t num)//输出配置器
{
	int i;
	for (i = 0; i < num; i++)
	{
		cout << vv[i] << ",";
	}
	cout << endl;
}

void main()
{
	vector<int>vt;
	vector<int>::iterator vtP;
	vector<int>::allocator_type vtA;

	allocator<int>Al;
	allocator<int>::pointer AlP;
	allocator<int>::const_pointer AlCP;

	int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	vt.assign(a, a + 10);
	printV(vt);
	int k = 6;
	AlCP = vtA.address(*find(vt.begin(), vt.end(), k)); //使用address
	cout << *AlCP << endl;

	AlP = Al.allocate(10);//分配内存
	int i = 0;
	for (auto b : a)
	{
		AlP[i++] = b;
	}
	printAl(AlP, 10);
	Al.deallocate(AlP, 10);//释放内存

	AlP = vtA.address(*find(vt.begin(), vt.end(), k));
	Al.destroy(AlP);
	Al.construct(AlP, 12);//修改数据
    printV(vt);

	allocator<int>::size_type  size;
	size = Al.max_size();
	cout << size << endl;
	
	system("pause");
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1467次
    • 积分:80
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类