qfedu-cpp-level/day4/homework/h6_2.cpp

137 lines
2.9 KiB
C++
Raw Normal View History

2023-07-27 21:04:06 +08:00
#include <iostream>
class ArrayList
{
private:
int *elements; // 存储元素的数组
int capacity; // 数组的容量
int count; // 当前元素的数量
public:
ArrayList()
{
capacity = 10; // 初始容量为10
elements = new int[capacity];
count = 0;
}
~ArrayList()
{
delete[] elements;
}
void add(int value)
{
if (count == capacity)
{
// 如果数组已满,扩展容量为原来的两倍
int newCapacity = capacity * 2;
int *newElements = new int[newCapacity];
for (int i = 0; i < count; i++)
{
newElements[i] = elements[i];
}
delete[] elements;
elements = newElements;
capacity = newCapacity;
}
elements[count] = value;
count++;
}
void remove(int index)
{
if (index >= 0 && index < count)
{
for (int i = index; i < count - 1; i++)
{
elements[i] = elements[i + 1];
}
count--;
}
}
int get(int index)
{
if (index >= 0 && index < count)
{
return elements[index];
}
return -1; // 返回一个特殊值表示索引无效
}
void print()
{
for (int i = 0; i < count; i++)
{
std::cout << elements[i] << " ";
}
std::cout << std::endl;
}
int size()
{
return count;
}
void sort(bool reversed = false)
{
for (int i = 0; i < count - 1; i++)
{
for (int j = 0; j < count - i - 1; j++)
{
if (reversed)
{
if (elements[j] < elements[j + 1])
{
int temp = elements[j];
elements[j] = elements[j + 1];
elements[j + 1] = temp;
}
}
else
{
if (elements[j] > elements[j + 1])
{
int temp = elements[j];
elements[j] = elements[j + 1];
elements[j + 1] = temp;
}
}
}
}
}
};
int main()
{
ArrayList list;
list.add(5);
list.add(2);
list.add(8);
list.add(1);
std::cout << "Original list: ";
list.print();
std::cout << "Size: " << list.size() << std::endl;
std::cout << "Element at index 2: " << list.get(2) << std::endl;
list.remove(1);
std::cout << "After removing element at index 1: ";
list.print();
std::cout << "Sorted list in ascending order: ";
list.sort();
list.print();
std::cout << "Sorted list in descending order: ";
list.sort(true);
list.print();
return 0;
}