www.pudn.com > calc5.zip > auto_vector.h


#if !defined AUTO_VECTOR 
#define AUTO_VECTOR 
//------------------------------------ 
//  auto_vector 
//  (c) Bartosz Milewski, 1998 
//------------------------------------ 
#include  
#include  
using std::auto_ptr; 
 
template 
class const_auto_iterator: public 
	std::iterator 
{ 
public: 
	const_auto_iterator () : _pp (0) {} 
	const_auto_iterator (auto_ptr const * pp) : _pp (pp) {} 
	bool operator != (const_auto_iterator const & it) const  
		{ return it._pp != _pp; } 
	const_auto_iterator operator++ (int) { return _pp++; } 
	const_auto_iterator operator++ () { return ++_pp; } 
	T const * operator * () { return _pp->get (); } 
	T const * operator-> () { return _pp->get (); } 
private: 
	auto_ptr const * _pp; 
}; 
 
template   
class auto_vector 
{ 
public: 
	explicit auto_vector (size_t capacity = 0) 
		: _arr (0), _end (0), _capacity (0) 
	{ 
		if (capacity != 0) 
			_arr = new auto_ptr [capacity]; 
		_capacity = capacity; 
	} 
	~auto_vector () 
	{ 
		delete []_arr; 
	} 
	size_t size () const { return _end; } 
	T const * operator [] (size_t i) const 
	{ 
		assert (i < _end); 
		return _arr [i].get (); 
	} 
	T * operator [] (size_t i) 
	{ 
		assert (i < _end); 
		return _arr [i].get (); 
	} 
	void assign (size_t i, auto_ptr & p) 
	{ 
		assert (i < _end); 
		_arr [i] = p; 
	} 
	void assign_direct (size_t i, T * p) 
	{ 
		assert (i < _end); 
		_arr [i].reset (ptr); 
	} 
	void push_back (auto_ptr & p) 
	{ 
		if (_end == _capacity) 
			grow (_end + 1); 
		_arr [_end++] = p; 
	} 
	auto_ptr pop_back () 
	{ 
		assert (_end != 0); 
		return _arr [--_end]; 
	} 
	typedef const_auto_iterator const_iterator; 
	const_iterator begin () const { return _arr; } 
	const_iterator end () const { return _arr + _end; } 
private:	 
	void grow (size_t reqCapacity); 
 
	auto_ptr  *_arr; 
	size_t		  _capacity; 
	size_t		  _end; 
}; 
 
template  
void auto_vector::grow (size_t reqCapacity) 
{ 
	size_t newCapacity = 2 * _capacity; 
	if (reqCapacity > newCapacity) 
		newCapacity = reqCapacity; 
	// allocate new array 
	auto_ptr * arrNew = new auto_ptr [newCapacity]; 
	// transfer all entries 
	for (size_t i = 0; i < _capacity; ++i) 
		arrNew [i] = _arr [i]; 
	_capacity = newCapacity; 
	// free old memory 
	delete []_arr; 
	// substitute new array for old array 
	_arr = arrNew; 
} 
 
 
#endif