/*****************************************************************************
 * 'main' illustrates the use of the allocator class from the <memory>
 * package.
 * **************************************************************************/
#include<iostream>
#include<iomanip>
#include<cstddef>/* This gives us size_t, a type to hold the size of an array.
		    */
#include<cstdlib>
#include<memory>

using std::cin; using std::cout;
using std::endl; using std::allocator;
using std::uninitialized_copy; using std::uninitialized_fill;


/* Replace the allocated array p with
 * 'new_size' copies of x, freeing the old memory. 
 */
int* value_fill(int*& p, size_t old_size, size_t new_size, int x)
{
	allocator<int> a;
       	a.deallocate(p, old_size);// free old memory
	p=a.allocate(new_size);// allocate new memory
	uninitialized_fill(p, p+new_size, x);// initialize new memory
	return p;
}

void show(int* p, size_t array_size)
{
	for( size_t i=0; i!=array_size; i++)
		cout<<p[i]<<" ";
}
	

int main()
{
	size_t repeats,n;
	int value;
	allocator<int> alloc;//Declare an allocator.
	int * tester;
	tester=alloc.allocate(1);// Allocate a single space.
	alloc.construct(tester,5);// Build a '5' in it.
	cout<<"\nThe memory holds a "<<*tester<<endl;
	*tester=8;
	cout<<"\nThe memory holds a "<<*tester<<endl;//Assign to the allocated
						     //location.
	alloc.deallocate(tester,1);
	tester=alloc.allocate(4);// Allocate 4 places.
	alloc.construct(tester,1);
	alloc.construct(tester+1,77);//Assign to the second place.
	cout<<"tester holds "<<*tester<<" in first position.\n";
	cout<<"tester holds "<<tester[1]<<" in second position.\n";//Indexing 
								   //works.
	cout<<endl;
	int* p=new int[6];
	p[0]=5; p[2]=10; p[3]=15;
	cout<<"The current contents of p: "<<endl;
	show(p,6);
	alloc.deallocate(tester,4);
	tester=alloc.allocate(6);
	cout<<"\nThe contentents of tester after allocation are\n";
	show(tester, 6);
	uninitialized_copy(p,p+6,tester);//Copy one memory block to another.
	cout<<endl<<"The current contents of tester: "<<endl;
	show(tester, 6);
	cout<<endl;
	cout<<"Please enter the new array size and the fill element: ";
	cin>>repeats>>value;
	value_fill(tester, 6,repeats,value);
	cout<<endl<<"The new contents of tester: "<<endl;
	show(tester, repeats);
	cout<<endl;	

	return 0;
}

	
