定义顺序表类模板,并初始化实现一个空int型顺序表;•实现顺序表的插入操作;·实现顺序表的按值查找操作;•实现顺序表的删除操作;•基于顺序表,实现两个int型集合的并集操作。
时间: 2024-12-24 13:30:17 浏览: 8
在C++中,我们可以创建一个顺序表类模板,用于存储整数。下面是一个基础的实现,包括空表的构造、插入、查找、删除以及并集操作:
```cpp
#include <iostream>
using namespace std;
template <typename T>
class SequenceList {
private:
int capacity;
T* elements;
int size;
public:
// 构造函数,初始化一个空列表
SequenceList(int initial_capacity = 0) : capacity(initial_capacity), elements(new T[capacity]), size(0) {}
~SequenceList() { delete[] elements; }
// 插入元素
void insert(T value) {
if (size == capacity) {
resize(capacity * 2); // 当满时,扩大容量
}
elements[size++] = value;
}
// 按值查找
bool search(const T& value) const {
for (int i = 0; i < size; ++i) {
if (elements[i] == value) {
return true;
}
}
return false;
}
// 删除元素
void remove(const T& value) {
for (int i = 0; i < size - 1; ++i) {
if (elements[i] == value) {
memmove(&elements[i], &elements[i + 1], sizeof(T) * (size - i - 1));
size--;
break;
}
}
}
// 并集操作,假设两个集合都没有重复元素
friend SequenceList<T> union_(const SequenceList<T>& list1, const SequenceList<T>& list2) {
SequenceList<T> result(list1.capacity + list2.capacity);
result.insert(list1.begin(), list1.end());
result.insert(list2.begin(), list2.end());
return result;
}
// 简化输出
void print() const {
for (int i = 0; i < size; ++i) {
cout << elements[i] << " ";
}
cout << endl;
}
private:
// 动态扩容
void resize(int new_capacity) {
T* new_elements = new T[new_capacity];
for (int i = 0; i < size; ++i) {
new_elements[i] = elements[i];
}
delete[] elements;
capacity = new_capacity;
elements = new_elements;
}
};
// 示例
int main() {
SequenceList<int> list;
list.insert(10);
list.insert(20);
list.insert(30);
cout << "Initial List: ";
list.print();
if (list.search(20)) {
cout << "Found 20" << endl;
} else {
cout << "Not found 20" << endl;
}
list.remove(20);
list.print();
SequenceList<int> other_list = {40, 50};
SequenceList<int> combined = union_(list, other_list);
cout << "Combined List: ";
combined.print();
return 0;
}
```
阅读全文