请你给出我所有函数的代码和主函数的代码
时间: 2024-02-19 13:58:09 浏览: 58
好的,以下是 DynamicArray 类模板的成员函数和菜单程序的代码示例:
```cpp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
template <typename T>
class DynamicArray
{
private:
int m_length; // 数组长度
int m_count; // 元素个数
T* m_data; // 数据指针
public:
// 构造函数和析构函数
DynamicArray()
{
m_length = 10;
m_count = 0;
m_data = new T[m_length];
}
~DynamicArray()
{
delete[] m_data;
}
// 添加元素
void AddItems(T aData[], int aLen)
{
if (m_count + aLen > m_length)
{
T* newData = new T[m_length + aLen];
memcpy(newData, m_data, m_count * sizeof(T));
delete[] m_data;
m_data = newData;
m_length = m_length + aLen;
}
memcpy(m_data + m_count, aData, aLen * sizeof(T));
m_count = m_count + aLen;
}
// 删除元素
bool RemoveAt(int index)
{
if (index < 0 || index >= m_count)
{
return false;
}
if (index == m_count - 1)
{
m_count--;
return true;
}
for (int i = index; i < m_count - 1; i++)
{
m_data[i] = m_data[i + 1];
}
m_count--;
return true;
}
// 插入元素
void InsertItem(int index, T aData)
{
if (index < 0)
{
index = 0;
}
if (index > m_count)
{
index = m_count;
}
if (m_count == m_length)
{
T* newData = new T[m_length * 2];
memcpy(newData, m_data, m_count * sizeof(T));
delete[] m_data;
m_data = newData;
m_length = m_length * 2;
}
for (int i = m_count; i > index; i--)
{
m_data[i] = m_data[i - 1];
}
m_data[index] = aData;
m_count++;
}
// 数组排序
void mySort()
{
sort(m_data, m_data + m_count);
}
// 其它功能
// ...
// 获取元素个数
int getCount()
{
return m_count;
}
// 获取数组长度
int getLength()
{
return m_length;
}
// 获取数据指针
T* getData()
{
return m_data;
}
};
// 菜单程序
int main()
{
DynamicArray<int> arr;
while (true)
{
system("cls"); // 清屏操作
cout << "请选择操作:" << endl;
cout << "1. 添加元素" << endl;
cout << "2. 删除元素" << endl;
cout << "3. 插入元素" << endl;
cout << "4. 数组排序" << endl;
cout << "5. 显示数组元素" << endl;
cout << "6. 退出程序" << endl;
int choice;
cin >> choice;
switch (choice)
{
case 1:
{
cout << "请输入要添加的元素个数:" << endl;
int count;
cin >> count;
int* data = new int[count];
for (int i = 0; i < count; i++)
{
cout << "请输入第" << i+1 << "个元素:" << endl;
cin >> data[i];
}
arr.AddItems(data, count);
delete[] data;
cout << "添加成功!" << endl;
system("pause");
break;
}
case 2:
{
cout << "请输入要删除的元素位置:" << endl;
int index;
cin >> index;
if (arr.RemoveAt(index))
{
cout << "删除成功!" << endl;
}
else
{
cout << "删除失败!" << endl;
}
system("pause");
break;
}
case 3:
{
cout << "请输入要插入的元素位置:" << endl;
int index;
cin >> index;
cout << "请输入要插入的元素:" << endl;
int data;
cin >> data;
arr.InsertItem(index, data);
cout << "插入成功!" << endl;
system("pause");
break;
}
case 4:
{
arr.mySort();
cout << "排序成功!" << endl;
system("pause");
break;
}
case 5:
{
int count = arr.getCount();
int* data = arr.getData();
cout << "数组元素为:" << endl;
for (int i = 0; i < count; i++)
{
cout << data[i] << " ";
}
cout << endl;
system("pause");
break;
}
case 6:
{
exit(0);
}
default:
{
cout << "输入错误,请重新输入!" << endl;
system("pause");
break;
}
}
}
return 0;
}
```
请注意,以上代码仅供参考,您需要根据实际需求进行修改和完善。
阅读全文