С#
Доделать методы:
Clear
Contains
CopyTo
IndexOf
Insert
Remove
RemoveAt
Далее:
1. Унаследовать вектор от интерфейса IClonable, и реализовать метод, который будет возвращать ссылку на созданную копию вектора.
2. Посмотреть, какие еще есть интерфейсы, от которых надо унаследовать вектор.
Код: using System.Collections;
using System.Numerics;
namespace SprInterfaces;
public class Vector : IList
{
private T[] _values;
// Default constructor
// Size constructor
// Array constuctor
// Copy constructor
public Vector()
{
_values = new T[0];
}
public Vector(int size)
{
if (size < 0)
throw new Exception("Vector size must be 0 or greater");
_values = new T[size];
}
public Vector(T[] values)
{
if (values == null)
throw new NullReferenceException("Given array is null");
_values = new T[values.Length];
for (int i = 0; i < values.Length; i++)
_values[i] = values[i];
}
public Vector(Vector other)
{
if (other == null)
throw new NullReferenceException("Given vector is null");
_values = new T[other._values.Length];
for (int i = 0; i < _values.Length; i++)
_values[i] = other._values[i];
}
public T this[int index]
{
get => _values[index];
set => _values[index] = value;
}
public int Count => _values.Length;
public bool IsReadOnly => false;
public void Add(T item)
{
// Расширяем массив на 1 ячейку
Array.Resize(ref _values, _values.Length + 1);
//_values[^1] = item;
_values[_values.Length - 1] = item;
}
// Очистить массив сделать размер 0
public void Clear()
{
throw new NotImplementedException();
}
// Вернуть true, если в массив есть элемент item, false if not
public bool Contains(T item)
{
throw new NotImplementedException();
}
// начиная с arrayIndex, скопировать в array данные из _values,
public void CopyTo(T[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public IEnumerator GetEnumerator()
{
IEnumerable enumerable = _values;
return enumerable.GetEnumerator();
}
// Линейный поиск - передается элемент, возвращается индекс
// Если не найдено - вернуть -1
public int IndexOf(T item)
{
// сравнивать Equals-ом
throw new NotImplementedException();
}
// Вставить в index новую ячейку с значением item
public void Insert(int index, T item)
{
throw new NotImplementedException();
}
// Удалить из массива ячейку со значением item (первую попавшуюся)
// Если нашло и удалило - true, если не нашло - false
public bool Remove(T item)
{
throw new NotImplementedException();
}
// Удалить из массив ячейку по индексу index
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
Ответы
1 Давайте реализуем оставшиеся методы для вашего вектора на языке C#:
using System;
public class Vector : ICloneable
{
private int[] array;
private int size;
public Vector(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be non-negative.");
array = new int[capacity];
size = 0;
}
public void Clear()
{
Array.Clear(array, 0, size);
size = 0;
}
public bool Contains(int item)
{
return IndexOf(item) != -1;
}
public void CopyTo(int[] destination, int index)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (index < 0 || index > destination.Length - size)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
Array.Copy(array, 0, destination, index, size);
}
public int IndexOf(int item)
{
for (int i = 0; i < size; i++)
{
if (array[i] == item)
return i;
}
return -1;
}
public void Insert(int index, int item)
{
if (index < 0 || index > size)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
if (size == array.Length)
Array.Resize(ref array, array.Length * 2);
Array.Copy(array, index, array, index + 1, size - index);
array[index] = item;
size++;
}
public void Remove(int item)
{
int index = IndexOf(item);
if (index != -1)
{
RemoveAt(index);
}
}
public void RemoveAt(int index)
{
if (index < 0 || index >= size)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
Array.Copy(array, index + 1, array, index, size - index - 1);
array[size - 1] = 0; // You may want to adjust this for reference types
size--;
}
public object Clone()
{
Vector clonedVector = new Vector(array.Length);
Array.Copy(array, clonedVector.array, size);
clonedVector.size = size;
return clonedVector;
}
// Add other methods as needed...
// For testing
public void Print()
{
for (int i = 0; i < size; i++)
{
Console.Write(array[i] + " ");
}
Console.WriteLine();
}
}
class Program
{
static void Main()
{
Vector vector = new Vector(5);
vector.Insert(0, 1);
vector.Insert(1, 2);
vector.Insert(2, 3);
Console.WriteLine("Original Vector:");
vector.Print();
// Test Clone method
Vector clonedVector = (Vector)vector.Clone();
Console.WriteLine("Cloned Vector:");
clonedVector.Print();
// Test other methods...
}
}
2 Ваш класс Vector уже реализует интерфейс IList. Однако, судя по комментариям и выбранным именам методов, некоторые из них еще не реализованы. Давайте дополним реализацию этих методов:
using System;
using System.Collections;
using System.Collections.Generic;
namespace SprInterfaces
{
public class Vector<T> : IList<T>
{
private T[] _values;
// Конструкторы и свойства оставляем без изменений...
public T this[int index]
{
get => _values[index];
set => _values[index] = value;
}
public int Count => _values.Length;
public bool IsReadOnly => false;
public void Add(T item)
{
Array.Resize(ref _values, _values.Length + 1);
_values[_values.Length - 1] = item;
}
public void Clear()
{
_values = new T[0];
}
public bool Contains(T item)
{
return Array.IndexOf(_values, item) != -1;
}
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_values, 0, array, arrayIndex, _values.Length);
}
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)_values).GetEnumerator();
}
public int IndexOf(T item)
{
return Array.IndexOf(_values, item);
}
public void Insert(int index, T item)
{
if (index < 0 || index > _values.Length)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
Array.Resize(ref _values, _values.Length + 1);
Array.Copy(_values, index, _values, index + 1, _values.Length - index - 1);
_values[index] = item;
}
public bool Remove(T item)
{
int index = IndexOf(item);
if (index != -1)
{
RemoveAt(index);
return true;
}
return false;
}
public void RemoveAt(int index)
{
if (index < 0 || index >= _values.Length)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
Array.Copy(_values, index + 1, _values, index, _values.Length - index - 1);
Array.Resize(ref _values, _values.Length - 1);
}
IEnumerator IEnumerable.GetEnumerator()
{
return _values.GetEnumerator();
}
}
}
Обратите внимание, что я добавил параметр типа T к вашему классу Vector, чтобы сделать его обобщенным. Это позволит использовать вектор для различных типов данных.