96 lines
2.5 KiB
C#
96 lines
2.5 KiB
C#
namespace Prac7Meow
|
|
{
|
|
internal class DynamicContainer<Meow>
|
|
{
|
|
private Meow[] _data;
|
|
private int _count;
|
|
private int _capacity;
|
|
|
|
public int Count => _count;
|
|
public int Capacity => _capacity;
|
|
|
|
public DynamicContainer(int initCap)
|
|
{
|
|
if (initCap < 1) initCap = 2;
|
|
|
|
_capacity = Utils.NearPow(initCap);
|
|
_data = new Meow[_capacity];
|
|
_count = 0;
|
|
}
|
|
|
|
private void Expand()
|
|
{
|
|
_capacity = (_capacity <= 0) ? 2 : _capacity * 2;
|
|
|
|
Meow[] data = new Meow[_capacity];
|
|
|
|
for (int i = 0; i < _count; i++) data[i] = _data[i];
|
|
|
|
_data = data;
|
|
}
|
|
|
|
private void EnsureCapacity(int needed)
|
|
{
|
|
if (needed <= _capacity) return;
|
|
|
|
while (_capacity < needed) Expand();
|
|
}
|
|
|
|
public void Add(Meow item)
|
|
{
|
|
EnsureCapacity(_count + 1);
|
|
_data[_count++] = item;
|
|
}
|
|
|
|
public void Insert(int index, Meow item)
|
|
{
|
|
if (index < 0 || index > _count)
|
|
throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} out of range [0..{_count}]");
|
|
|
|
EnsureCapacity(_count + 1);
|
|
|
|
for (int i = _count; i > index; i--) _data[i] = _data[i - 1];
|
|
|
|
_data[index] = item;
|
|
_count++;
|
|
}
|
|
|
|
public void RemoveAt(int index)
|
|
{
|
|
if (index < 0 || index >= _count)
|
|
throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} out of range [0..{_count - 1}]");
|
|
|
|
for (int i = index; i < _count - 1; i++) _data[i] = _data[i + 1];
|
|
|
|
_data[_count - 1] = default!;
|
|
_count--;
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
for (int i = 0; i < _count; i++)
|
|
_data[i] = default!;
|
|
|
|
_count = 0;
|
|
}
|
|
|
|
public Meow this[int index]
|
|
{
|
|
get
|
|
{
|
|
if (index < 0 || index >= _count)
|
|
throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} out of range [0..{_count - 1}]");
|
|
|
|
return _data[index];
|
|
}
|
|
set
|
|
{
|
|
if (index < 0 || index >= _count)
|
|
throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} out of range [0..{_count - 1}]");
|
|
|
|
_data[index] = value;
|
|
}
|
|
}
|
|
}
|
|
}
|