#include <iostream>
#include <iterator>
#include <memory>
#include <algorithm>
using namespace std;
namespace mylib {
template<typename Ty,
typename Allocator = std::allocator<Ty> >
class array {
public:
//type定义
typedef Ty value_type;
typedef size_t size_type;
typedef ptrdiff_t diffecence_type;
typedef Ty* pointer;
typedef const Ty* const_pointer;
typedef Ty& reference;
typedef const Ty& const_reference;
//构造函数集合
array(size_type sz = 0,
Allocator a = Allocator())
: alloc(a), _size(sz), ia(NULL)
{
get_memory();
std::uninitialized_fill_n(ia, _size, 0);
}
array(const array<Ty>& coll)
: alloc(coll.alloc), _size(coll.size()), ia(NULL)
{
get_memory();
std::uninitialized_copy(coll.begin(), coll.end(),
ia);
}
array(const_pointer cap,
const size_type sz,
Allocator a = Allocator())
: alloc(a), _size(sz), ia(NULL)
{
get_memory();
std::uninitialized_copy(cap, &cap[sz-1], ia);
}
~array(void)
{
for(size_type i = 0; i < _size; ++i)
{
alloc.destroy(&ia[i]);
}
alloc.deallocate(ia, _size);
}
//运算符重载集合
const bool operator== (const array<Ty>& coll) const
{
if(_size != coll.size())
return false;
for(size_type i = 0; i < _size; ++i)
{
if(ia[i] != coll[i])
return false;
}
return true;
}
const bool operator!= (const array<Ty>& coll ) const
{
if(_size != coll.size())
return true;
for(size_type i = 0; i < _size; ++i)
{
if(ia[i] != coll[i])
return true;
}
return false;
}
const array<Ty>& operator= (const array<Ty>& coll)
{
if(this == &coll)
return *this;
if(ia != NULL)
{
for(size_type i = 0; i < _size; ++i)
alloc.destro(&ia[i]);
alloc.deallocate(ia, _size);
}
_size = coll.size();
get_memory();
std::uninitialized_copy(coll.begin(), coll.end(),
ia);
return coll;
}
reference operator[] (const size_type index)
{
return ia[index];
}
const_reference operator[] (const size_type index) const
{
return ia[index];
}
//内置方法
const_pointer begin(void) const
{
return ia;
}
const_pointer end(void) const
{
return &ia[_size-1];
}
const size_type size(void) const
{
return _size;
}
const value_type min(void) const
{
return *std::min_element(ia, &ia[_size-1]);
}
const value_type max(void) const
{
return *std::max_element(ia, &ia[_size-1]);
}
private:
//私有函数
void get_memory(void)
{
ia = alloc.allocate(_size);
}
//私有数据
Allocator alloc;
pointer ia;
size_type _size;
};
}
int main(void)
{
using mylib::array;
ostream_iterator<int> outit(cout,"\t");
int a[] = {1,5,4,8,5,6};
array<int> collx(10);
array<int> colly(a,sizeof(a)/sizeof(a[0]));
copy(collx.begin(), collx.end(),
outit);
cout << endl;
for(size_t i = 0; i < collx.size(); ++i)
collx[i] = i;
copy(collx.begin(), collx.end(),
outit);
cout << endl;
cout << collx.max() << "\t" << collx.min() << endl;
copy(colly.begin(), colly.end(),
outit);
cout << endl;
cout << colly.max() << "\t" << colly.min() << endl;
cin.get();
}