#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class SequenceList {
private:
vector<T> elements;
public:
// 获取顺序表的长度
int length() const {
return elements.size();
}
// 在指定位置插入元素
void insertElement(int index, const T& element) {
if (index >= 0 && index <= length()) {
elements.insert(elements.begin() + index, element);
} else {
throw out_of_range("Index out of range");
}
}
// 删除指定位置的元素
void deleteElement(int index) {
if (index >= 0 && index < length()) {
elements.erase(elements.begin() + index);
} else {
throw out_of_range("Index out of range");
}
}
// 显示顺序表中的元素
void display() const {
for (const T& element : elements) {
cout << element << " ";
}
cout << endl;
}
};
int main() {
// 使用 int 类型的顺序表
SequenceList<int> intList;
intList.insertElement(0, 10);
intList.insertElement(1, 20);
intList.insertElement(2, 30);
cout << "Length: " << intList.length() << endl;
intList.display();
// 使用 string 类型的顺序表
SequenceList<string> stringList;
stringList.insertElement(0, "Apple");
stringList.insertElement(1, "Banana");
stringList.insertElement(2, "Orange");
cout << "Length: " << stringList.length() << endl;
stringList.display();
return 0;
}
【多态&模板&异常处理&表达式】
最新推荐文章于 2024-07-18 23:31:00 发布