📄 array.h
字号:
#ifndef _LANG_ARRAY_H
#define _LANG_ARRAY_H
#include <assert.h>
namespace lang
{
/**
* Flexible array. Arrays are meant to be used
* as part of higher abstraction level objects so
* they don't have functionality for reference counting.
* @param T Type of array element. Copy and default ctor should be nothrow.
*
* @ingroup lang
*/
template <class T> class Array
{
public:
/**
* Creates an empty array.
*/
Array() :
m_a(0), m_size(0), m_cap(0)
{
}
/**
* Creates an array of specified size.
* @exception OutOfMemoryException
*/
explicit Array( int size, const T& defaultvalue=T() ) :
m_a(0), m_size(0), m_cap(0)
{
resize( size, defaultvalue );
}
/**
* Copy by value.
*/
Array( const Array<T>& other ) :
m_a(0), m_size(0), m_cap(0)
{
*this = other;
}
///
~Array()
{
delete[] m_a;
}
/**
* Copy by value.
* @exception OutOfMemoryException
*/
Array<T>& operator=( const Array<T>& other );
/**
* Returns ith element from the array.
*/
T& operator[]( int index )
{
assert( index >= 0 && index < m_size );
return m_a[index];
}
/**
* Adds an element to the end of the array.
* @exception OutOfMemoryException
*/
void add( const T& item );
/**
* Adds an element before specified index.
* @exception OutOfMemoryException
*/
void add( int index, const T& item );
/**
* Removes an element at specified index.
*/
void remove( int index );
/**
* Sets number of elements in the array.
* @exception OutOfMemoryException
*/
void resize( int size, const T& defaultvalue=T() );
/**
* Sets number of elements in the array to 0.
*/
void clear()
{
resize( 0 );
}
/**
* Returns pointer to the beginning of the array (inclusive).
*/
T* begin()
{
return m_a;
}
/**
* Returns pointer to the end of the array (exclusive).
*/
T* end()
{
return m_a+m_size;
}
/**
* Returns last element in the array (inclusive).
*/
T& last()
{
assert( m_size > 0 );
return m_a[m_size-1];
}
/**
* Returns ith element from the array.
*/
const T& operator[]( int index ) const
{
assert( index >= 0 && index < m_size );
return m_a[index];
}
/**
* Returns number of elements in the array.
*/
int size() const
{
return m_size;
}
/**
* Returns pointer to the beginning of the array (inclusive).
*/
const T* begin() const
{
return m_a;
}
/**
* Returns pointer to the end of the array (exclusive).
*/
const T* end() const
{
return m_a+m_size;
}
/**
* Returns last element in the array (inclusive).
*/
const T& last() const
{
assert( m_size > 0 );
return m_a[m_size-1];
}
/**
* Returns index of the item in the array or -1 if not found.
*/
int indexOf( const T& item ) const;
private:
T* m_a;
int m_size;
int m_cap;
/**
* Allocates buffer for n elements.
* @exception OutOfMemoryException
*/
void realloc( int size );
/**
* Copy in reverse order.
*/
void rcopy( T* dst, const T* src, int count );
};
#include <lang/Array.inl>
} // lang
#endif // _LANG_ARRAY_H
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -