编写代码:用模板类定义对象,实现顺序表的一些基本操作
时间: 2023-03-25 12:03:18 浏览: 111
可以回答这个问题。以下是一个模板类定义对象,实现顺序表的一些基本操作的示例代码:
```
#include <iostream>
using namespace std;
template <typename T>
class SeqList {
private:
T *data;
int size;
int capacity;
public:
SeqList(int cap = 10) {
data = new T[cap];
size = ;
capacity = cap;
}
~SeqList() {
delete[] data;
}
int getSize() const {
return size;
}
bool isEmpty() const {
return size == ;
}
bool isFull() const {
return size == capacity;
}
void clear() {
size = ;
}
void insert(int pos, const T &elem) {
if (isFull()) {
cout << "Error: SeqList is full." << endl;
return;
}
if (pos < || pos > size) {
cout << "Error: Invalid position." << endl;
return;
}
for (int i = size; i > pos; i--) {
data[i] = data[i - 1];
}
data[pos] = elem;
size++;
}
void remove(int pos) {
if (isEmpty()) {
cout << "Error: SeqList is empty." << endl;
return;
}
if (pos < || pos >= size) {
cout << "Error: Invalid position." << endl;
return;
}
for (int i = pos; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
}
T &operator[](int pos) {
if (pos < || pos >= size) {
cout << "Error: Invalid position." << endl;
exit(1);
}
return data[pos];
}
const T &operator[](int pos) const {
if (pos < || pos >= size) {
cout << "Error: Invalid position." << endl;
exit(1);
}
return data[pos];
}
};
int main() {
SeqList<int> list(5);
cout << "Size: " << list.getSize() << endl;
cout << "Is empty? " << (list.isEmpty() ? "Yes" : "No") << endl;
cout << "Is full? " << (list.isFull() ? "Yes" : "No") << endl;
list.insert(, 1);
list.insert(1, 2);
list.insert(2, 3);
list.insert(3, 4);
list.insert(4, 5);
cout << "Size: " << list.getSize() << endl;
cout << "Is empty? " << (list.isEmpty() ? "Yes" : "No") << endl;
cout << "Is full? " << (list.isFull() ? "Yes" : "No") << endl;
for (int i = ; i < list.getSize(); i++) {
cout << list[i] << " ";
}
cout << endl;
list.remove(2);
cout << "Size: " << list.getSize() << endl;
cout << "Is empty? " << (list.isEmpty() ? "Yes" : "No") << endl;
cout << "Is full? " << (list.isFull() ? "Yes" : "No") << endl;
for (int i = ; i < list.getSize(); i++) {
cout << list[i] << " ";
}
cout << endl;
return ;
}
```
阅读全文