用C++编译:新建一个顺序表,采用顺序存储的方式,将输入的数据存入顺序表,并将输入的元素输出,并完成以下基本操作: (1).删除指定位置的元素; (2).向指定位置插入元素; (3).查找某元素在线性表中的位置。
时间: 2024-10-22 11:05:18 浏览: 25
在C++中,你可以创建一个简单的顺序列表(也称为数组或动态数组)来实现这些功能。首先,你需要一个模板类`SequentialList`来定义顺序表的基本结构,包括数据成员、构造函数、迭代器以及增删查的操作。
```cpp
template <typename T>
class SequentialList {
private:
T* data; // 存储元素的指针
size_t size; // 序列长度
size_t capacity; // 容量
public:
SequentialList(size_t initial_capacity = 0) : data(new T[initial_capacity]), size(0), capacity(initial_capacity) {}
~SequentialList() { delete[] data; }
void addElement(T element) {
if (size == capacity) {
resize(capacity * 2); // 当满时扩大容量
}
data[size++] = element;
}
void deleteElementAt(size_t position) {
if (position >= size || position < 0) {
throw std::out_of_range("Position out of range");
}
for (size_t i = position; i < size - 1; ++i) {
data[i] = data[i + 1];
}
size--;
}
void insertElementAt(size_t position, T element) {
if (position > size) {
throw std::invalid_argument("Invalid insertion position");
}
if (size == capacity) {
resize(capacity * 2);
}
memmove(data + position + 1, data + position, sizeof(T) * (size - position));
data[position] = element;
size++;
}
size_t findElement(const T& element) const {
for (size_t i = 0; i < size; ++i) {
if (data[i] == element) {
return i;
}
}
return -1; // 如果未找到则返回-1
}
// ...其他需要的辅助函数(如遍历等)
private:
void resize(size_t new_capacity) {
T* temp = new T[new_capacity];
for (size_t i = 0; i < size; ++i) {
temp[i] = data[i];
}
delete[] data;
data = temp;
capacity = new_capacity;
}
};
```
现在你可以使用这个类来创建一个顺序表并执行所需的操作:
```cpp
int main() {
SequentialList<int> list(5);
list.addElement(10);
list.addElement(20);
list.addElement(30);
std::cout << "Elements before deletion: ";
for (auto elem : list) {
std::cout << elem << ' ';
}
std::cout << '\n';
list.deleteElementAt(1); // 删除索引为1的元素
std::cout << "After deleting element at index 1: ";
for (auto elem : list) {
std::cout << elem << ' ';
}
std::cout << '\n';
list.insertElementAt(2, 40); // 插入元素40到索引2的位置
std::cout << "After inserting 40 at index 2: ";
for (auto elem : list) {
std::cout << elem << ' ';
}
std::cout << '\n';
int search_result = list.findElement(30);
if (search_result != -1) {
std::cout << "Element found at index " << search_result << '\n';
} else {
std::cout << "Element not found.\n";
}
return 0;
}
```
阅读全文