函数配置器的举例

来源:互联网 发布:java xbootclasspath 编辑:程序博客网 时间:2024/04/20 04:47

配置器的定义:

在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)); //使用addresscout << *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
原创粉丝点击